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!
Top comments (0)