[rspec-users] Stubs and Object Constructor

Pat Maddox patmaddox at me.com
Wed Mar 23 06:25:00 EDT 2011


On Mar 20, 2011, at 9:38 PM, andyl wrote:

> OK - I got this working using mocha and the 'any_instance' method.  
> 
> A gist with working examples is here: https://gist.github.com/879029
> 
> It looks like rspec mocks had an 'any_instance' method, but it was removed because it promoted 'bad practice'.
> 
> I'm curious to understand how 'any_instance' promotes bad practice.  I found it useful in my situation, to stub out slow network code that crushed my test performance.
> 
> - Andy 

A class in Ruby is an object. When you call Test2.stub(:sayhi), you are defining a stub method on the object that is the Test2 class. This class object manufactures instances, whose methods are the instance methods defined by Test2. So basically you were defining the stub on a completely different object than you thought you were.

To answer your question, any_instance was rejected for a long time because it does not align with the RSpec team's opinion of making dependencies explicit. That said, any_instance will make it into an upcoming release. Not because it's a good idea ;) but because so many people have clamored for it and frequently use mocha primarily for that feature.

Pat


More information about the rspec-users mailing list