Created
August 27, 2012 15:21
-
-
Save ernsheong/3489451 to your computer and use it in GitHub Desktop.
Exploring let and let! in RSpec. Puzzled by how let and let! behaves, I decided to take https://www.relishapp.com/rspec/rspec-core/docs/helper-methods/let-and-let and modify it further to inspect let and let!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'spec_helper' | |
# comment out `config.order = "random"` in spec_helper or run rspec with `--order default` configuration (just for illustration) | |
# I have Database Cleaner set up in spec_helper too | |
$count1 = 0 | |
$count2 = 0 | |
describe "let and let!" do | |
describe "let!" do | |
invocation_order = [] | |
let!(:count) do | |
FactoryGirl.create(:user) | |
invocation_order << :let! | |
$count1 += 1 | |
end | |
it "calls the helper method in a before hook" do | |
invocation_order << :example | |
invocation_order.should == [:let!, :example] | |
$count1.should eq(1) # count was called before example implicitly | |
count.should eq(1) # returns memoized version | |
User.count.should == 1 | |
end | |
it "recalls the helper method and executes the block before each example" do | |
invocation_order.should == [:let!, :example, :let!] | |
$count1.should eq(2) | |
count.should eq(2) # helper method only executed once before example | |
invocation_order.should == [:let!, :example, :let!] | |
User.count.should == 1 # database is teared down after each example | |
end | |
end | |
describe "let" do | |
let(:count) do | |
FactoryGirl.create(:user) | |
$count2 += 1 | |
end | |
it "memoizes the value within an example" do | |
count.should eq(1) | |
count.should eq(1) # helper method is only executed once per example | |
User.count.should == 1 | |
end | |
it "is not cached across examples" do | |
count.should eq(2) | |
count.should eq(2) | |
User.count.should == 1 | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment