あなたはインスタンス変数を模擬することはできません。メソッドをモックすることしかできません。 1つの方法は、another_member
をラップし、そのメソッドをモックするメソッドOneClass
を定義することです。
class OneClass
def initialize(*args)
end
def my_method()
if another_member.another_method1() then
another_member.another_method2()
end
another_member.another_method3()
end
private
def another_member
@another_member ||= AnotherClass.new()
end
end
ただし、コードを記述してテストする方法はありません。この場合、より良いアプローチは、Dependency Injectionというパターンを使用することです。
依存関係を初期化子に渡します。
class OneClass
def initialize(another: AnotherClass, whatever:, somethingelse:)
@another_member = another.new()
end
def my_method()
if @another_member.another_method1() then
@another_member.another_method2()
end
@another_member.another_method3()
end
end
(注:キーワード引数を使用しましたが、そうする必要はありません。標準のargsアプローチを使用することもできます)。
次に、テストスイートでは、テストオブジェクトを提供するだけです。
let(:test_another) {
Class.new do
def another_method1
:foo
end
def another_method2
:bar
end
def another_method3
:baz
end
end
}
it "does something" do
subject = OneClass.new(another: test_another)
# ...
end
このアプローチにはいくつかの利点があります。特に、テストでモックを使用することは避け、実際にはオブジェクトを単独でテストします。