Zeke Fast
Zeke Fast

Reputation: 530

How to let stub to return instance on which it is called in case of using any_instance?

For example, I have class A.

class A
end

And want in spec return instance of that class from stubbed method.

A.any_instance.stub(:my_method).and_return(<here is the same instance on which my_method is called should got>)

Is that possible to make something similar in RSpec?

Upvotes: 4

Views: 131

Answers (1)

ShadyKiller
ShadyKiller

Reputation: 710

This will do the trick for you :

A.any_instance.stub(:my_method) do |*args|
    instance = RSpec::Mocks::space.send(:receivers).last
end

I dug this out from the rspec code here : rspec github code

P.S. : This depends entirely on rspec implementation and may change in the future. The background is a little complex to explain here. I may add that in future.

Upvotes: 1

Related Questions