0
votes

I am trying to clean up some specs by placing things that were instantiated in each example into a let method based upon the docs here: https://www.relishapp.com/rspec/rspec-core/v/2-13/docs/helper-methods/let-and-let!. The ObjectConnection piece in the second spec is created as part of main_menu. If I do it via rails console, it works fine.

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

When I run, I get:

 undefined method `global_id' for nil:NilClass 

in second example

Is this how this should be working? Or do I need to declare menu=FactoryGirl.create(:main_menu) in each example?

2

2 Answers

2
votes

Use let! if you want to test a side effect of the instantiation of an object.

The regular let is lazy loaded.

1
votes

The let statement block is only called when the variable is referenced. Since it isn't referenced in your second example, it isn't called. You should be able to just a add something like

x = menu

at the top of that example to get that let block called.

It's probably an anti-pattern to use a let statement for its side effects, due to confusions like this one.