Is there a way to undo Mocha stubbing of any_instance in Test::Unit
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!"
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