rspec の let と let!
Ruby Ruby on Rails
Published: 2019-06-13

やったこと

rspec の let と let! の違いについて調べてみます。

確認環境

$ ruby --version
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin17]

$ rails --version
Rails 5.2.3

$ gem list | grep rspec-rails
rspec-rails (3.8.2)

調査

  • let は遅延評価
  • let! はテスト前に実行される

let を使う

spec/models/task6_spec.rb

require 'rails_helper'

RSpec.describe Task, type: :model do
  let(:user) { create(:user) }
  let(:task) { create(:task) }

  it 'test1' do
  end
end

出力結果

$ rspec spec/models/task6_spec.rb
.

Finished in 0.01818 seconds (files took 1.66 seconds to load)
1 example, 0 failures

let! を使う

spec/models/task6_spec.rb

require 'rails_helper'

RSpec.describe Task, type: :model do
  let!(:user) { create(:user) }
  let!(:task) { create(:task) }

  it 'test1' do
  end
end

出力結果

$ rspec spec/models/task6_spec.rb
F

Failures:

  1) Task test1
     Failure/Error: let!(:user) { create(:user) }

     KeyError:
       Factory not registered: "user"
     # ./spec/models/task6_spec.rb:7:in `block (2 levels) in <top (required)>'
     # ------------------
     # --- Caused by: ---
     # KeyError:
     #   key not found: "user"
     #   ./spec/models/task6_spec.rb:7:in `block (2 levels) in <top (required)>'

Finished in 0.00288 seconds (files took 1.65 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/models/task6_spec.rb:10 # Task test1

参考