[RSpec 3] RSpec の () と {} の違い
matcher がブロックを受け取れるかどうかで使い分ける。
[markdown]
## 症状
`expect { result }.to` と書くと、
“`ruby
describe ‘#map_upto’ do
let(:result) { @fizz_buzz.map_upto(15, @fizz_buzz.method(:fizzbuzz)) }
it ” do
expect { result }.to eq(@ans)
end
end
“`
`rspec` の実行で止まる。
“`prettyprinted
Failures:
1) FizzBuzz#map_upto
Failure/Error: expect { result }.to eq(@ans)
You must pass an argument rather than a block to use the provided matcher (eq [1, 2, “Fizz”, 4, “Buzz”, “Fizz”, 7, 8, “Fizz”, “Buzz”, 11, “Fizz”, 13, 14, “FizzBuzz”]), or the matcher must implement `supports_block_expectations?`.
# ./spec/fizzbuzz_spec.rb:20:in `block (3 levels) in
“`
表示のとおり
> You must pass an argument rather than a block to use the provided matcher
`eq` という matcher がブロックを受け取れないから。
引数でないとダメと言われている。
## 対応
`expect(result).to` でエラーなしとなる。
“`ruby
describe ‘#map_upto’ do
let(:result) { @fizz_buzz.map_upto(15, @fizz_buzz.method(:fizzbuzz)) }
it ” do
expect(result).to eq(@ans)
end
end
“`
ドキュメントをよく見ると、小括弧 `()` と中括弧 `{}` が使い分けられていた。
> * [Built in matchers – RSpec Expectations – RSpec – Relish](https://www.relishapp.com/rspec/rspec-expectations/v/3-5/docs/built-in-matchers)
もう少し調査すると、ソースを読まれている方がいた。
> * [should を捨て expect を使うようになった、たった一つの理由 – MUGENUP技術ブログ](http://mugenup-tech.hatenadiary.com/entry/2013/11/26/123933)
[/markdown]