DEV Community

Ilya N. Zykin
Ilya N. Zykin

Posted on

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!

Top comments (0)