Justin Francis
2010-Mar-04 22:48 UTC
[mocha-developer] sharing any_instance stubs with subclasses
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
James Mead
2010-Mar-07 17:53 UTC
[mocha-developer] sharing any_instance stubs with subclasses
Hi Justin, Thanks for trying to send us a patch. I don''t think attachments make it through on Google Groups. Have you considered forking Mocha on GitHub [1] and sending me a pull request? Alternatively you could use Gist [2] or Pastie [3] to show us the code. I have to confess, I haven''t used Mocha''s any_instance functionality for a long time. I find there are usually simpler ways of stubbing methods and setting expectations. Well done for finding that old mailing list thread. There''s another more recent one here [4]. Have you tried running the Mocha tests with your patch applied? Also it would be really helpful if you could write new acceptance tests like these [5] to describe the behaviour you are expecting and/or identify existing tests which describe behaviour you are not expecting. If you''re interested in working out how you might avoid the use of any_instance, it might be worth posting some code and explaining what you''re trying to do and we can see if we can come up with an alternative approach. Cheers, James. [1] http://github.com/floehopper/mocha [2] http://gist.github.com/ [3] http://pastie.org/ [4] http://groups.google.com/group/mocha-developer/browse_thread/thread/99981af7c86dad5e