使用let和FactoryGirl有两个例子 - 不知道为什么这不起作用

时间:2013-05-30 16:59:38

标签: ruby-on-rails rspec

我试图通过将每个示例中实例化的内容放入基于此处文档的let方法来清理一些规范:https://www.relishapp.com/rspec/rspec-core/v/2-13/docs/helper-methods/let-and-let !.第二个规范中的ObjectConnection部分是作为main_menu的一部分创建的。如果我通过rails console进行,它可以正常工作。

describe "shall comment on items" do

  let(:menu) { FactoryGirl.create(:main_menu) } # i am assuming that I have access to a menu variable

  # this one works
  it 'should submit a message to a valid location' do
    kt=menu.location
    xhr :post, :create_message, {content: "here is my content", associated_global_id: kt.global_id }
    response.code.should == "200"
  end

  # this one doesn't
  it 'should submit a message to a valid object connection' do
    pairing=ObjectConnection.first # multiple ObjectConnections are created as part of the main_menu factory
    xhr :post, :create_message, {content: "here is my approval of your pairing seneor", associated_global_id: pairing.global_id } # this is where the error is
    response.code.should == "200"
  end
end

当我跑步时,我得到:

 undefined method `global_id' for nil:NilClass 
第二个例子中的

这是应该如何工作的?或者我是否需要在每个示例中声明menu = FactoryGirl.create(:main_menu)?

2 个答案:

答案 0 :(得分:2)

如果要测试对象实例化的副作用,请使用let!

常规let是延迟加载的。

答案 1 :(得分:1)

仅在引用变量时调用let语句块。由于在第二个示例中未引用它,因此不会调用它。你应该能够添加像

这样的东西
x = menu

在该示例的顶部,以便调用let块。

由于像这样的混淆,使用let语句来表示其副作用可能是一种反模式。