Search code examples
rubyrspectddbdd

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


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?


Solution

  • 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.