Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to force RSpec to re-evaluate a let statement?

Tags:

tdd

ruby

rspec

bdd

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?

like image 964
B Seven Avatar asked Apr 02 '13 17:04

B Seven


People also ask

How does let work in RSpec?

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.

Why use let in RSpec?

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.

Where can a let Block be defined?

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.


1 Answers

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.

like image 141
Stuart M Avatar answered Oct 13 '22 21:10

Stuart M