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

[Rails / Rspec] instance_doubleの使い分け:第二引数の有無による違い

Posted at

概要

表題の違いについて、まとめました。

結論

  • 第二引数なしの場合
    • instance_doubleMockのみ作成される
    • allowによるスタブ設定が必要

  • 第二引数ありの場合
    • Mockの作成と、スタブの定義を同時に実施される

コード

ここでは XmlGenerator クラスの callインスタンスメソッドをスタブします。

第二引数なしの場合

  1. instance_double で モックを作成
  2. allow で スタブの定義
let(:xml_generator) { instance_double(XmlGenerator) }

before do
  allow(xml_generator).to receive(:call).and_return('<xml>Test</xml>')
end

第二引数ありの場合

  1. instance_double で モックとスタブを作成
let(:xml_generator) { instance_double(XmlGenerator, call: '<xml>Test</xml>') }

メリット / デメリット

第二引数なしの場合

  • メリット
    • 柔軟性が高く、複雑なスタブ設定や複数のメソッドのスタブを後から個別に定義できる
  • デメリット
    • コード量が増え、記述が冗長になる可能性がある

第二引数ありの場合

  • メリット
    • モック作成と同時にスタブの定義ができるため、コードが簡潔で読みやすい
  • デメリット
    • 複雑なスタブ設定には向かず、シンプルな戻り値の定義に限定される場合が多い

まとめ

以上です。
メリデメを理解した上で使い分けると、可読性の高いテストコードが記載できそうですね!

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