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

【RSpec】先にallow to receiveを書いて、後から"呼び出されたか"を確認する方法

Posted at

あるメソッドが「呼び出されたかどうか」をテストする場合、

it '...' do
  expect(...).to receive(...)

  # 処理
end

のように書くと、「処理後に結果を確認する」という一般的なテストの順序と逆になり、「beforeが他のテストと共有できない」「なんだか気持ちわるい」といった問題が発生します。

そんなときは have_received を使うとスッキリ書けるかもしれません。

class Foo
  def hoge; end

  def fuga
    hoge
  end
end

RSpec.describe Foo do
  let(:foo) { Foo.new }

  describe "Foo#fuga" do
    subject { foo.fuga }

    before do
      allow(foo).to receive(:hoge).and_return("test")
      subject
    end

    it "fugaメソッドを呼び出したとき、hogeが呼び出されること" do
      expect(foo).to have_received(:hoge)
    end
  end
end

参考URL

4
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
4
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?