やったこと
Rails5 で使っている rspec の allow と expect の違いについて調べます。
確認環境
$ 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)
調査
spec/models/task3_spec.rb
require 'rails_helper'
RSpec.describe Task, type: :model do
it 'test1 allow success' do
o = Object.new
allow(o).to receive(:display).and_return(:display_value2)
expect(o.display).to eq(:display_value2)
end
it 'test1 expect fail' do
o = Object.new
expect(o).to receive(:display).and_return(:display_value)
end
it 'test1 expect success' do
o = Object.new
expect(o).to receive(:display).and_return(:display_value)
expect(o.display).to eq(:display_value)
end
end
出力結果
$ bundle exec rspec spec/models/task3_spec.rb
.F.
Failures:
1) Task test1 expect fail
Failure/Error: expect(o).to receive(:display).and_return(:display_value)
(#<Object:0x00007fef8b614e28>).display(*(any args))
expected: 1 time with any arguments
received: 0 times with any arguments
# ./spec/models/task3_spec.rb:15:in `block (2 levels) in <top (required)>'
Finished in 0.02301 seconds (files took 1.13 seconds to load)
3 examples, 1 failure
Failed examples:
rspec ./spec/models/task3_spec.rb:12 # Task test1 expect fail
allow と expect の違いは、呼び出しの検査をするかどうかになります。
expect で定義したメソッドを呼び出さないとエラーになります。