LoginSignup
56
29

More than 5 years have passed since last update.

RSpecで配列をテストするマッチャの使い分け

Last updated at Posted at 2018-10-03

rspecで配列を検証する際にはマッチャとしてeqを使わない方が良い(と思っている)
eqを使用すると、内部的に==で比較を行うため、配列の要素と、要素の並び順も比較する


expect([1, 2, 3]).to eq [1, 3, 2] #=> false
expect([1, 2, 3]).to eq [1, 2, 3] #=> true

#この方法だと配列の要素と要素の並び順を両方とも比較していることが伝わりにくい。

配列の要素と順番が両方とも期待値と一致していることを検証するにはmatchマッチャを使用する

expect([1, 2, 3]).to match [1, 3, 2] #=> false
expect([1, 2, 3]).to match [1, 2, 3] #=> true

配列の要素のみ期待値と一致していることをテストするためにはcontain_exactlyかmatch_arrayマッチャを使用する


expect([1, 2, 3]).to contain_exactly(1, 3, 2) #=> true
expect([1, 2, 3]).to match_array([1, 3, 2]) #=> true

*配列をテストする際にmatchでなくeqを優先して使用するようなパターンをご存知の方、大変お手数ですがご指摘を頂けますとありがたいです!:sweat:

参考
https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/contain-exactly-matcher

56
29
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
56
29