LoginSignup
39
33

More than 5 years have passed since last update.

rspecのstubとmockについて

Posted at

モックとスタブの使い分け

モック

「オブジェクトのメソッドがどう呼ばれて何を返すか」というインタフェースも含めたテストのために使う

スタブ

テストをスムーズに行うために「あるオブジェクトのメソッドが呼ばれたら、ある戻り値を返す」ために使う

# object.stub(:is_dummy?).and_return(true)
User.stub(:is_dummy?).and_return(true)


この書き方から

# allow(object).to receive(method).and_return(return value)
allow(User).to receive(:is_dummy?).and_return(true)

に書き換える

こっちのがいいのかな

allow_any_instance_of(Widget).to receive(:name).and_return("Wibble")
expect_any_instance_of(Widget).to receive(:name).and_return("Wobble")

参考

https://github.com/rspec/rspec-mocks
http://stackoverflow.com/questions/17566690/object-any-instance-should-receive-vs-expect-to-receive
http://nabewata07.hatenablog.com/entry/ruby/rspec/mocks2-14/syntax-and-spy
http://morizyun.github.io/blog/rspec-model-controller-ruby-rails/

39
33
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
39
33