2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rspecで複数のモデルのカウントが増加しないことを検証する

Last updated at Posted at 2021-06-26

会社でRspec書いてて、「createアクションを動かしたときにAモデルとBモデルのカウントがともに増加しないこと」を検証する必要があった。その時

expect {
  post :create, params
  }.not_to change(Hoge, :count).and change(Fuga, :count)

のように書くと以下のエラーが発生

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_to change ... and change ...みたいな書き方はできませんよ、という話。

これを解消するにはエラー文にある通り以下の1行をはさむ。changeの否定としてnot_changeというのを定義しますよという意味。

# change マッチャの否定を定義する
RSpec::Matchers.define_negated_matcher :not_change, :change
expect {
  post :create, params
  }.to not_change(Hoge, :count).and notchange(Fuga, :count)

なんでnot_to change ... and change ...使えないの?って感じだけどまぁ1行挟むくらいならいいか…

Rspecのマッチャは奥が深いわねー

参考
https://qiita.com/harashoo/items/a4f1e01d300b6d329dee

2
0
0

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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?