为rspec测试创建模型的临时条目

时间:2017-08-31 10:32:24

标签: ruby-on-rails ruby unit-testing ruby-on-rails-4 rspec

我在控制器中有一条flash消息,我想用rspec测试它。 在我的控制器中,如果数据库为空,我设置flash[:notice],否则为零。

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

然后在rspec文件中我想测试两种情况:
i:当flash[:notice]设置为&#34时;数据库为空"
ii:当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测试通过,但第二个失败。我不知道如何断言第二个测试用例的数据库不为空。

谢谢

2 个答案:

答案 0 :(得分:0)

您已走上正轨,但未正确使用factory-girl。方法build(代码中有buil)初始化记录,但不会保留记录(例如,它与{{1}类似带有属性)。

要将记录保存到数据库中,应使用方法User.new,但在实际向create发出请求之前。

以下内容(我不知道请求是如何进行的,所以show仅作为示例),使用contexts,它允许您将测试分成有意义的块:

get :show

或者规范可以分为两个块:一个是数据库为空时,另一个是数据库不为空时(当你在空/非空数据库上执行多个规范时很有用)

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

答案 1 :(得分:0)

问题在于您使用y而不是FactoryGirl.build

当您使用FactoryGirl.create时,它会创建模型的新实例,但不会将其保存到数据库中,而build会将该实例保存在数据库中。

有关详细信息,请参阅此处:https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#using-factories