88
54

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 5 years have passed since last update.

rspec3でメソッドが呼び出されたかテストする

Last updated at Posted at 2016-03-31

TL/DR

rspecのテストを書いてる時
メソッドが呼び出されているかどうかだけ
確認したい時、ありませんか?

そんな時のやり方です。

rspec-mocksのSpyという機能を使います

Test Spies
https://github.com/rspec/rspec-mocks#test-spies

# メソッドを監視するコード
allow(オブジェクト).to receive(:メソッド名)
# テストコード
expect(オブジェクト).to have_received(:メソッド名).once

のような感じ。

code

例えばこんなメソッドがあって、
振る舞いのテストを作成したい時に

class Order
  def create(order)
    if order.save
      Bill.create(order)
      NoticeMailer.new(email: order.email).send()
      'success!'
    else
      'error!'
    end
  end
end

Bill.create(order)や
NoticeMailer.new(email: order.email).send()は
別のとこでテストしているから、もういいんだよ。
でもちゃんと呼ばれているかだけ
確認しときたいって時。

  describe '#create' do
    let(:new_order){ build(:new_order) }

    before do
      allow(Bill).to receive(:create)
      allow(NoticeMailer).to receive_message_chain(:new, :send)
    end
    context 'no user' do
      it do
        Order.create(new_order)
        expect(Bill).to have_received(:create).once
        expect(NoticeMailer.new).to have_received(:send).once
      end
    end
  end

こんな感じになります。

environment

$ rails -v
Rails 4.2.6
$ bundle exec rspec -v
3.4.4

thank you ..

88
54
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
88
54

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?