let and let!

My conclusion is that both let and let! cached value within examples, but not cross examples. If another example calls it, both of them will be executed. The only difference is that let is lazy, which means it won’t be executed if it is not invoked, but that is not true for let!.

“let” is only evaluated when invoked, and keeps the same value within a scope

https://www.relishapp.com/rspec/rspec-core/v/2-6/docs/helper-methods/let-and-let

(:let!) is forcefully evaluated before each method call.

$count = 0
describe "let!" do
  invocation_order = []

  let!(:count) do
    invocation_order << :let!
    $count += 1
  end

  it "calls the helper method in a before hook" do
    invocation_order << :example
    invocation_order.should == [:let!, :example]
    count.should eq(1)
  end

  it "calls the helper method again" do
    count.should eq(2)
  end
end

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s