RSpec で複数の項目が変更されたかどうかをテストする
Compound expression という仕組みで、ひとつの expect に対して複数の matcher をメソッドチェーンでつなげることができる
たとえば、以下のように
code: example2_spec.rb
expect {
model.do_something
}.to change { model.hoge }.from(1).to(2)
.and change { model.fuga }.from('').to('FUGA')
しかし、これとは逆に変化していないことをテストする場合にはひと工夫が必要になる
code: example2_spec.r
expect {
model.do_something
}.not_to change { model.hoge }
.and_not_to change { model.fuga }
のように書けるかとおもったが、 and_not_to というものは存在していない
code: example3_spec
expect {
model.do_something
}.not_to change { model.hoge }
.and change { model.fuga }.from('').to('') # fuga 初期値は ''
こうしても、以下のようにエラーとなる。
code:error
NotImplementedError:
expect(...).not_to matcher.and matcher is not supported, since it creates a bit of an ambiguity. Instead, define negated versions of whatever matchers you wish to negate with RSpec::Matchers.define_negated_matcher and use expect(...).to matcher.and matcher.
どうやら自分で not_xxx みたいな matcher を作る必要がありそう。といっても以下ををかくだけ
code: spec/rails_helper.rb
RSpec::Matchers.define_negated_matcher :not_change, :change
そうすると、以下のように書ける
code: example4_spec.rb
expect {
model.do_something
}.to not_change { model.hoge }
.and not_change { model.fuga }
参考
RSpec 3.1 has been released!
Composing Matchers - RSpec Expectations - RSpec - Relish
テストです
ああああ