かあさん、RSpec Mock 2.14にTest Spyがあるようで...

RSpec Mock 2.14にはexpectっぽい記述が追加されましたね。http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/

# Old
foo.should_receive(:bar)
foo.should_receive(:bar).with(:buzz)
foo.should_receive(:bar).exactly(3).times

# New
expect(foo).to receive(:bar)
expect(foo).to receive(:bar).with(:buzz)
expect(foo).to receive(:bar).exactly(3).times

それだけかと思っていたら、DoubleパターンのTest Spyが実装されています。(Test Spyについては、日本語だと http://goyoki.hatenablog.com/entry/20120301/1330608789 の Test Spyが分かりやすいかも)待ってましたよ!!(もしかして、undocumentedだっただけで、元々実装されてましたかね?)
以下は、http://myronmars.to/n/dev-blog/2013/07/rspec-2-14-is-released の「Mocks: Spies」のサンプルコードです。

# non_spy_spec.rb
mailer = double("Mailer")
expect(mailer).to receive(:deliver_welcome_email).with(an_instance_of(User))
UserCreationService.new(mailer).create_user(params)

# spy_spec.rb
mailer = double("Mailer", deliver_welcome_email: nil)
UserCreationService.new(mailer).create_user(params)
expect(mailer).to have_received(:deliver_welcome_email).with(an_instance_of(User))

とっても、いいね!

--- 参考URL

--- PR広告
記事を読んでくださり、ありがとうございます。もしよろしければ、この記事の著者が開発・運営している無料のカクテルレシピ提供サービス「かくってる?」をお試しください。