問題
たとえば、次のようなメソッドを書いていたとする。
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
サンプルコード