有没有办法在Test :: Unit中撤消任何实例的Mocha存根

就像这个问题一样 ,我也在使用Ryan Bates的nifty_scaffold。 它具有使用Mocha的any_instance方法强制在隐藏在控制器后面的模型对象中的“无效”状态的理想方面。

与我链接的问题不同,我没有使用RSpec,而是使用Test :: Unit。 这意味着这两个以RSpec为中心的解决方案对我不起作用。

是否有一般(即:使用Test :: Unit)方法来删除any_instance存根? 我相信它在我的测试中导致了一个错误,我想validation一下。

碰巧,Mocha 0.10.0允许在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!" 

摩卡不提供这样的function。 但是你可以自己实现它。

关于mocha我们应该知道的第一件事是mocha实际上替换了原始方法。 因此,为了以后能够恢复这些方法,您必须保留对前者的引用。 它可以通过以下方式轻松实现: alias new_method old_method 。 必须嘲笑old_method 之前完成。

现在,要取消模拟方法,您只需要使用alias old_method new_method

请考虑以下代码:

 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 aa, "b" A.class_eval {alias a unmocked_a} assert aa, "a" end end 

如果你想一次性删除所有的存根/期望,那么你可以使用mocha_teardown(例如,调用self.mocha_teardown)来实现。

但是,在这种情况下可能会有点破坏性。