From justinf at wantsa.com Thu Mar 4 17:48:34 2010 From: justinf at wantsa.com (Justin Francis) Date: Thu, 04 Mar 2010 14:48:34 -0800 Subject: [mocha-developer] sharing any_instance stubs with subclasses Message-ID: <4B9038C2.7010508@wantsa.com> 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: #.t() satisfied expectations: - allowed any number of times, not yet invoked: #.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 From jamesmead44 at gmail.com Sun Mar 7 12:53:00 2010 From: jamesmead44 at gmail.com (James Mead) Date: Sun, 7 Mar 2010 17:53:00 +0000 Subject: [mocha-developer] sharing any_instance stubs with subclasses In-Reply-To: <4B9038C2.7010508@wantsa.com> References: <4B9038C2.7010508@wantsa.com> Message-ID: <1db558f01003070953i32177f1bpd164024d8a244f1a@mail.gmail.com> 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