2012-07-27 82 views
23

我是使用RSpec在使用MySQL數據庫的Rails應用程序中編寫測試的新手。我定義我的燈具和我加載它們在我的規格如下:RSpec中的燈具

before(:all) do 
    fixtures :student 
end 

這是否申報保存在我的學生表燈具定義的數據還是隻是加載表中的數據,而測試在所有測試運行後運行並將其從表中移除?

+10

取而代之的是燈具,請試試看[factory_girl](http://www.fabricationgem.org/)或[製造](http://www.fabricationgem.org/)。 – 2013-11-02 13:21:45

回答

-1

這取決於您配置RSpec的方式。有關更多詳細信息,請參見here

1

before(:all)保留確切的數據,因爲它已加載/創建一次。你做你的事情,並在測試結束時停留。這就是爲什麼bui的鏈接有after(:all)銷燬或使用before(:each); @var.reload!;end從以前的測試中獲取最新的數據。我可以看到在嵌套rspec描述塊中使用這種方法。

16

如果你想塊前使用與RSpec的固定裝置,在描述塊指定賽程,不是內:

describe StudentsController do 
    fixtures :students 

    before do 
    # more test setup 
    end 
end 

您的學生燈具將被裝載到學生表,然後在回滾使用數據庫事務結束每個測試。

+1

https://www.relishapp.com/rspec/rspec-rails/docs/model-specs/transactional-examples#run-in-transactions-with-fixture – nruth 2015-01-10 03:06:44

3

首先:您不能在:all/:context/:suite hook中使用方法fixtures。不要試圖在這些掛鉤中使用燈具(如post(:my_post))。

您可以僅在describe/context塊中準備Fixtures,因爲Infuse先前寫入。

呼叫

fixtures :students, :teachers 

任何數據不加載到數據庫!只准備幫手方法studentsteachers。 當您首次嘗試訪問它們時,需要的記錄會被懶惰地加載。之前

dan=students(:dan) 

這會加載學生和老師delete all from table + insert fixtures的方式。

所以,如果你準備在之前(:上下文)鉤一些學生,他們將會消失!

插入記錄只在測試套件中完成一次。

來自燈具的記錄在測試套件結束時不會被刪除。在下一次測試套件運行時,它們將被刪除並重新插入。

例如:

#students.yml 
    dan: 
    name: Dan 
    paul: 
    name: Paul 

#teachers.yml 
    snape: 
     name: Severus 




describe Student do 
    fixtures :students, :teachers 

    before(:context) do 
    @james=Student.create!(name: "James") 
    end 

    it "have name" do 
    expect(Student.find(@james.id).to be_present 
    expect(Student.count).to eq 1 
    expect(Teacher.count).to eq 0 

    students(:dan) 

    expect(Student.find_by_name(@james.name).to be_blank 
    expect(Student.count).to eq 2 
    expect(Teacher.count).to eq 1 

    end 
end 


#but when fixtures are in DB (after first call), all works as expected (by me) 

describe Teacher do 
    fixtures :teachers #was loade in previous tests 

    before(:context) do 
    @james=Student.create!(name: "James") 
    @thomas=Teacher.create!(name: "Thomas") 
    end 

    it "have name" do 
    expect(Teacher.find(@thomas.id).to be_present 
    expect(Student.count).to eq 3 # :dan, :paul, @james 
    expect(Teacher.count).to eq 2 # :snape, @thomas 

    students(:dan) 

    expect(Teacher.find_by_name(@thomas.name).to be_present 
    expect(Student.count).to eq 3 
    expect(Teacher.count).to eq 2 

    end 
end 

在測試的所有預期以上將通過

如果這些測試中(在接下來的套件)和以該順序再次運行,比預期

expect(Student.count).to eq 1 

將不會被滿足!將有3名學生(:丹,:保羅和新鮮的@james)。所有這些將在students(:dan)之前被刪除,並且只有:paul和:dan會再次被插入。

+1

是啊!我發現了在所有測試之前加載所有燈具的技巧。只需添加RSpec.configure {| config | config.global_fixtures =:all}並直接在spec_helper中測試,它將嘗試訪問任何燈具。這樣所有的燈具都會提前加載。 – Foton 2016-09-29 14:14:11