This example is a bit contrived, but explains the use case well.
let( :number_of_users ){ User.count }
it 'counts users' do
User.create
number_of_users.should == 1
User.create
number_of_users.should == 2
end
This test fails because number_of_users
is only evaluated once, and gets stale. Is there a way to have this re-evaluated each time it is called?
What does let do? let generates a method whose return value is memoized after the first call. This is known as lazy loading because the value is not loaded into memory until the method is called.
Use let to wrap your testing variables Both of these will help RSpec understand when to create the variables, and help our tests run correctly.
The let method should be called inside an example group. The first argument is the name of a variable to define. The let method is passed a block that computes the value of the variable, and the block will be called if the value of the variable is ever needed. In other words, let variables are lazily evaluated.
You can just define a regular method:
def number_of_users
User.count
end
it 'counts users' do
User.create
number_of_users.should == 1
User.create
number_of_users.should == 2
end
See this blog post for some more details, including how to store the helper methods in a separate module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With