Recently I needed to ‘unstub’ a method in Mocha. Browsing Mocha documentation and googling yielded no results. Apparently, Mocha doesn’t support a concept of ‘unstubbing’, i.e. recovering original implementation of a method that has been stubbed. After a little hacking, I found out that it’s quite easy (though not necessarily elegant) to call original implementation.
Let’s imagine we have a code like this:
class LolCatTest < Test::Unit::TestCase def setup LolCat.any_instance.stubs(:eat_cheeseburger).returns(nil) end def test_cheeseburger kitteh = LolCat.new assert_not_nil kitteh.eat_cheeseburger end end
eat_cheeseburger method, because it performs some lengthy calculation or interacts with some external service and we normally don’t want it to be called in tests. But if there is some special test that has to call original implementation for some reason (like
test_cheeseburger above), we need to resort to some hacking:
class LolCatTest < Test::Unit::TestCase def setup LolCat.send(:alias_method, :i_can_has_cheeseburger, :eat_cheeseburger) LolCat.any_instance.stubs(:eat_cheeseburger).returns(nil) end def test_cheeseburger kitteh = LolCat.new kitteh.stubs(:eat_cheeseburger).returns(kitteh.i_can_has_cheeseburger) assert_not_nil kitteh.eat_cheeseburger end end
There are two new elements in this example. First, before we stub
eat_cheeseburger, we use
alias_method to add a new name for this method. Second, we stub
eat_cheeseburger to call the aliased method, thus bypassing the original stub.
If you know a better way to do this, I would be glad to hear about it. Or maybe there is some official way of unstubbing methods in Mocha, that I couldn’t find?