Ilya N. Zykin
Posted on April 24, 2023
After years being out of the Rails ecosystem I was curious what is the difference between let
and let!
in rspec tests. I just forgot.
There is a simple case to demonstrate:
require 'rails_helper'
RSpec.describe User, type: :model do
describe 'Creating.' do
let!(:user) { create(:user) }
it 'Exists' do
expect(User.count).to eq 1
end
end
end
1) User Creating. Exists
Failure/Error: expect(User.count).to eq 1
And with let!
require 'rails_helper'
RSpec.describe User, type: :model do
describe 'Creating.' do
let!(:user) { create(:user) }
it 'Exists' do
expect(User.count).to eq 1
end
end
end
It gives: User Creating. Exists
Conclusion
With let
we create an object when we first time to use it.
With let!
we create an object when we declare it.
Happy Coding!
💖 💪 🙅 🚩
Ilya N. Zykin
Posted on April 24, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.