参考資料
1.公式サイト
2.expect
とis_expected
の違い
比較マッチャー使用例
require 'rails_helper' RSpec.describe '比較matchers' do let(:target_num) { 14 } let(:target_word) { 'navy' } describe '数値の比較' do # (ウロ覚え書き🙄)戻り値のオブジェクト(modelなど)の属性を取得する場合、 # 下記の様な記述でactual.〜で属性の値が取得できたはず。 subject(:actual) { target_num } # 戻り値のオブジェクトのみを比較する場合は下記 # subject { target_num } describe '成功するケース' do # 下記記述ならsubjectだけでもOK! it { is_expected.to be < 15 } # 下記記述をするなら、subject(:戻り値)の記述が必要 it { expect(actual).to be > 13 } # 残りはis_expectedで記述してみた it { is_expected.to be <= 14 } it { is_expected.to be >= 14 } end describe '失敗するケース' do context '数値の場合' do it { is_expected.to be > 15 } end context '数値と文字列を比較した場合' do it { is_expected.to be < 'a' } end end end describe '文字列の比較' do subject(:actual) { target_word } describe '成功するケース' do it { is_expected.to be < 'olive' } it { is_expected.to be > 'maroon' } it { is_expected.to be <= 'navy' } it { is_expected.to be >= 'navy' } end describe '失敗するケース' do it { is_expected.to be > 'olive' } end end end
実行結果
$ bundle exec rspec spec/sample/comparison_matcher_spec.rb 比較matchers 数値の比較 成功するケース is expected to be < 15 is expected to be > 13 is expected to be <= 14 is expected to be >= 14 失敗するケース 数値の場合 is expected to be > 15 (FAILED - 1) 数値と文字列を比較した場合 is expected to be < a (FAILED - 2) 文字列の比較 成功するケース is expected to be < olive is expected to be > maroon is expected to be <= navy is expected to be >= navy 失敗するケース is expected to be > olive (FAILED - 3) Failures: 1) 比較matchers 数値の比較 失敗するケース 数値の場合 is expected to be > 15 Failure/Error: it { is_expected.to be > 15 } expected: > 15 got: 14 # ./spec/sample/comparison_matcher_spec.rb:30:in `block (5 levels) in <top (required)>' 2) 比較matchers 数値の比較 失敗するケース 数値と文字列を比較した場合 is expected to be < a Failure/Error: it { is_expected.to be < 'a' } expected: < "a" got: 14 # ./spec/sample/comparison_matcher_spec.rb:34:in `block (5 levels) in <top (required)>' 3) 比較matchers 文字列の比較 失敗するケース is expected to be > olive Failure/Error: it { is_expected.to be > 'olive' } expected: > "olive" got: "navy" # ./spec/sample/comparison_matcher_spec.rb:51:in `block (4 levels) in <top (required)>' Finished in 0.05387 seconds (files took 1.33 seconds to load) 11 examples, 3 failures Failed examples: rspec ./spec/sample/comparison_matcher_spec.rb:30 # 比較matchers 数値の比較 失敗するケース 数値の場合 is expected to be > 15 rspec ./spec/sample/comparison_matcher_spec.rb:34 # 比較matchers 数値の比較 失敗するケース 数値と文字列を比較した場合 is expected to be < a rspec ./spec/sample/comparison_matcher_spec.rb:51 # 比較matchers 文字列の比較 失敗するケース is expected to be > olive
おまけ
expect
とis_expected
の違い
参考資料にis_expected
が出てきたので'expect'との違いを調べてみた。
引用
つまり、同じオブジェクトかどうかを比較したい場合は上の方法(is_expected)、 同じ属性を持っているかどうかを比較したい場合は下の方の方法(expected)を 使えば良さそうだ
... そういえば、最初のRubyの現場で「is_expected
使うべし」論が出ていた気がする。
参考資料2のindigo-lainさんの説明で、「is_expected
使うべし」論を少し理解できた気がする。
indigo-lainさん、ありがとうございます🙇🏻♀️