You can't mock an instance variable. You can only mock methods. One option is to define a method inside OneClass that wraps the another_member, and mock that method.
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
However, you don't have to, there is a better way to write and test your code. In this case a better approach to mocking is to use a pattern called Dependency Injection.
You pass your dependency to the initializer.
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
(Note I used keyword arguments, but you don't have to. You can also use the standard args approach).
Then, in the test suite you simply provide the test object.
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
There are several advantages of this approach. In particular, you avoid using mock in the tests and you really test the object in isolation.