When to use let, let! and before in RSpec
Public
09 Jul 15:42

When to use let, let! and before.

let

When we want to set a variable that we will later use in the examples.

let(:user) { create :user }

it 'does something to user' do
  do_something_to_user(user) # user is initialized here (for example the record is created)
  
  expect(user).to be_stuff
end

it 'is tricky' do
  expect(User.count).to eq(0) # we never called `user` so it's not created in this example
end

let!

When we want to set a variable that we will later use in the examples, BUT we want to initialize it right away.

let!(:user) { create :user }

it 'does something to user' do
  do_something_to_users(User.all) # We used let!, so the user already exists
  
  expect(user).to be_stuff
end

it 'is less tricky' do
  expect(User.count).to eq(1) # the user was created before the example
end

before

There is a problem in the last example. We use let! and assign user to a variable, but we never use it.
This pollutes our namespace with unneeded names and makes our tests harder to understand.
If you don’t need access to the variable, simply use before.

before { create_list :user, 10 }

it 'is simple and clear' do
  expect(User.count).to eq(10)
end

Comments

Empty! You must sign in to add comments.