RSpec. let and let!

the_teacher

Ilya N. Zykin

Posted on April 24, 2023

RSpec. let and let!

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
Enter fullscreen mode Exit fullscreen mode
  1) User Creating. Exists
     Failure/Error: expect(User.count).to eq 1
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!

💖 💪 🙅 🚩
the_teacher
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.

Related