LoginSignup
33
32

More than 5 years have passed since last update.

メソッド内で生成されるインスタンスをstubしたいときにdouble rubyとrspec-mocksを使って書く

Posted at

問題

たとえば、次のようなメソッドを書いていたとする。

def run_with_deep_dependent_other_library
  lib = DependentLibrary.new
  attributes = lib.configure_some_attributes(self)
  run_some_routines(attributes)
end

とある理由(たとえば、いろんなところから参照され、そのたびにinstanceを生成するのは面倒なので内部で生成)から、メソッド内でインスタンスを内部で生成している。
そのメソッドをテストしたいけど、内部で生成しているインスタンスはテスト環境で再現することが困難な場合stubしたい。
だが、直接その生成しているインスタンスにアクセスできない。
どうするか?

double ruby

double rubyでは、any_instance_ofを使う。

describe C do
  describe "#run_with_deep_dependent_other_library" do
    let(:attributes) { {foo: 'bar'} }
    before do
      any_instance_of(DependentLibrary) do |o|
        stub(o).configure_some_attributes { attributes }
      end
    end
    # ...
  end
end

rspec-mocks

rspec_mocksでは、any_instanceを使う。
詳しい使い方は、any_instanceのspecを読むこと。

describe C do
  describe "#run_with_deep_dependent_other_library" do
    let(:attributes) { {foo: 'bar'} }
    before do
      DependentLibrary.any_instance.stub(configure_some_attributes: attributes)
    end
    #...
  end
end

サンプルコード

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