[mocha-developer] sharing any_instance stubs with subclasses

Justin Francis justinf at wantsa.com
Thu Mar 4 17:48:34 EST 2010


Hello,

I ran into a problem where stubbing `any_instance` of a parent class' 
method would effectively prevent anyone from calling that method on a 
subclass instance (using 0.9.8). I know something similar was brought up 
about two years ago 
(http://rubyforge.org/pipermail/mocha-developer/2008-January/000521.html)

===================
class A
   def t()
     'in A'
   end
end

class B < A
end

A.any_instance.stubs(:t).returns('stubbed')
b = B.new
b.t       # throws error
===================

Here, calling b.t would give the following error:

==================
Mocha::ExpectationError: unexpected invocation: #<AnyInstance:B>.t()
satisfied expectations:
- allowed any number of times, not yet invoked: 
#<AnyInstance:A>.t(any_parameters)
==================

Anyway, I needed this to work, so I implemented a naive solution where 
subclasses will share their parents "AnyInstance" instances and attached 
the patch to this message.

Thought this might be useful to others, even though I realise it does 
not fully solve the issue (in this example, if B.t was defined as an 
overridden method, B.t would still be called, not the stubbed version in A).

Thanks,

Justin Francis



More information about the mocha-developer mailing list