简体   繁体   中英

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: "user@example.com",
                 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM