Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec: let versus let with an exclamation mark

Can comeone explain to me why it is necessary to use let! as opposed to let in this case? The test only passes when I include the !. I thought I understood that let would automatically execute before each "it" statement within that block, but apparently that is not the case.

describe Artist do

  before do
  @artist = Artist.new(name: "Example User", email: "[email protected]",
                 password: "foobar", password_confirmation: "foobar")
  end
  subject { @artist }

  describe "virtual requests" do
    let!(:virtual1) { FactoryGirl.create(:virtual_request, artist: @artist ) }
    let!(:virtual2) { FactoryGirl.create(:virtual_request, artist: @artist ) }

    it "should be multiple" do
      @artist.virtual_requests.count.should == 2 
    end
  end
end
like image 473
Matt Ramirez Avatar asked Oct 25 '13 16:10

Matt Ramirez


1 Answers

Because let is lazy. If you don't call it, it won't do anything.

Instead, let! is active and will execute the code inside its block when you pass by.

In your code, if you replace let! with let, your test won't pass.

The reason is you havn't called :virtual1 and :virtual2 afterwards, so the code inside there block won't be executed and the record won't be created by FactoryGirl.

like image 195
Billy Chan Avatar answered Sep 23 '22 05:09

Billy Chan