33

Much like this question, I too am using Ryan Bates's nifty_scaffold. It has the desirable aspect of using Mocha's any_instance method to force an "invalid" state in model objects buried behind the controller.

Unlike the question I linked to, I'm not using RSpec, but Test::Unit. That means that the two RSpec-centric solutions there won't work for me.

Is there a general (ie: works with Test::Unit) way to remove the any_instance stubbing? I believe that it's causing a bug in my tests, and I'd like to verify that.

Vega
  • 27,856
  • 27
  • 95
  • 103
Craig Walker
  • 49,871
  • 54
  • 152
  • 212

3 Answers3

52

As it happens, Mocha 0.10.0 allows unstubbing on any_instance().

str = "Not Stubbed!"
String.any_instance.stubs(:to_s).returns("Stubbed!")
puts str.to_s   # "Stubbed!"
String.any_instance.unstub(:to_s)
puts str.to_s   # "Not Stubbed!"
sameers
  • 4,855
  • 3
  • 35
  • 44
Craig Walker
  • 49,871
  • 54
  • 152
  • 212
4

Mocha does not provide such a functionality. However you can implement it yourself.

The first thing we should know about mocha is that mocha actually replaces the original methods when you stub them. So in order to be able to restore these methods later, you must keep a reference to the former ones. It can be easily achieved by: alias new_method old_method. It must be done before mocking the old_method.

Now, to unmock a method, you only need to alias old_method new_method.

Consider the following code:

class A
    def a
        true
    end
end


class TestA < Test::Unit::TestCase
    def test_undo_mock
        a = A.new
        A.class_eval {alias unmocked_a a}

        A.any_instance.stubs(:a).returns("b")
        assert a.a, "b"

        A.class_eval {alias a unmocked_a}
        assert a.a, "a"
    end
end
Yossi
  • 11,778
  • 2
  • 53
  • 66
  • Excellent. This looks like something that could be added/monkeypatched into Mocha too. – Craig Walker May 24 '10 at 16:05
  • 1
    I've never felt the need for this functionality, but there is a ticket - http://floehopper.lighthouseapp.com/projects/22289-mocha/tickets/69-allow-unstubbing-of-methods if you want to lobby for the change. It would be great if you have some examples of why you'd want to use it. – James Mead Sep 26 '10 at 16:51
  • 2
    I have added unstubbing functionality - Mocha::ObjectMethods#unstub - see http://mocha.rubyforge.org/classes/Mocha/ObjectMethods.html#M000009 – James Mead Dec 02 '10 at 11:08
  • 2
    Mocha now has this; see my new answer. – Craig Walker Dec 21 '11 at 19:30
0

If you want to remove all your stubs/expectations in one go, then you can do that using mocha_teardown (eg. call self.mocha_teardown).

May be a little bit destructive in this case, however.

ChrisW
  • 332
  • 3
  • 7