LoginSignup
1
2

More than 1 year has passed since last update.

Rspec | should_receive は何をしている?

Last updated at Posted at 2015-11-04

should_receive は、あるクラスのメソッドが呼び出されることを検証する。

成功

SomeModel.create が呼ばれることを期待する。

it do
  SomeModel.should_receive(:create)
  SomeModel.create
end

例として、ここでは直後に SomeModel.create を呼んでいるが。

たとえば他のメソッドの中や。コントローラの処理の中など。
どこからか一度でも SomeModel.create が呼ばれれば成功する。

失敗

should_receive のにメソッドが実行されても意味が無い。

it do
  SomeModel.create
  SomeModel.should_receive(:create)
end

.with

.with は、そのメソッドが、特定の引数をつけて呼ばれることを検証する。

成功する例

it do
  SomeModel.should_receive(:create).with)(title: 'Bible')
  SomeModel.create(title: 'Bible')
end

失敗

it do
  SomeModel.should_receive(:create).with)(title: 'Bible')
  SomeModel.create(title: 'Gone with the wind')
end

補足

should は古いので、 新しいバージョンでは expect を使うこと。
http://qiita.com/shuhei/items/58452ad1572b7e40c150

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

メンター受付

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