2017-08-31 61 views
0

我在控制器中有一個flash消息,我想用rspec來測試它。 在我的控制器中,如果數據庫爲空,則設置flash[:notice],否則爲零。
創建一個rspec測試模型的臨時入口

def show 
    if(User.first.nil?) 
    flash[:notice] = "database is empty!" 
    end 
end 

然後在RSpec的文件我想測試兩種情況:
我:當flash[:notice]設置爲「數據庫爲空」
二:當flash[:notice]未設置爲幹啥

def show 
    it "assigns a "database is empty!" to flash[:notice]" 
    expect(flash[:notice]).to eq("database is empty!") 
    end 

    it "does not assign anything to flash[:notice]" 
    FactoryGirl.buil(:user) 
    expect(flash[:notice]).to be_nil 
    end 
end 

第一次rspec測試通過但第二次失敗。我不知道如何斷言第二個測試用例的數據庫不是空的。

謝謝

回答

0

你在正確的軌道上,但使用不當factory-girl。方法build(代碼中有buil)初始化記錄,但不保留它(例如,它就像具有屬性的User.new)。

要將記錄保存到數據庫中,應使用方法create,但在實際向show提出請求之前。

類似下面的(我不知道請求是怎麼做,所以get :show只是舉例),使用contexts,它允許你測試分成有意義的塊:

context "request for the show on empty database" do 
    before { get :show, params: { id: id } } 

    it "assigns a 'database is empty!' to flash[:notice]" 
    expect(flash[:notice]).to eq("database is empty!") 
    end 
end 

context "request for the show on nonempty database" do 
    before do 
    FactoryGirl.create(:user) 
    get :show, params: { id: id } 
    end 

    it "does not assign anything to flash[:notice]" 
    expect(flash[:notice]).to be_nil 
    end 
end 

或者規格可以分成兩大塊:一個當數據庫是空的,另一個當數據庫不爲空(有用的,當你必須要對空/非空數據庫中執行多個規格)

context "when database is empty" do 
    context "and show is requested" do 
    before { get :show, params: { id: id } } 

    it "flash[:notice] is assigned to 'database is empty!'" 
     expect(flash[:notice]).to eq("database is empty!") 
    end 
    end 
end 

context "when database is not empty" do 
    before { FactoryGirl.create(:user) } 

    context "and show is requested" do 

    before { get :show, params: { id: id } } 

    it "does not assign anything to flash[:notice]" 
     expect(flash[:notice]).to be_nil 
    end 
    end 
end 
+0

呢'之前do'創建之前每個「它」單獨塊工廠女孩的實例?如果這樣做,那麼第一個測試用例將失敗,因爲如果數據庫表不是空的,那麼將不會有閃存消息。 –

+0

是的,你需要把它分成另一個'context'塊 –

+0

你能編輯你的答案並教我關於使用上下文嗎?上下文實際上做了什麼? –

0

的問題是,你正在使用FactoryGirl.build而不是FactoryGirl.create

當您使用build時,它會創建模型的新實例,但不會將其保存到數據庫,而create將該實例保存在數據庫中。

欲瞭解更多信息,請參見這裏:https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#using-factories

+0

但如果我使用創建然後第一次rspec測試失敗下次我運行rspec命令。因爲第一個「it」會測試是否設置了flash通知,並且只在數據庫表爲空時設置。 –