2017-08-31 59 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通知,并且只在数据库表为空时设置。 –