2010-05-24 48 views
17

中取消any_instance的Mocha stubbing,就像this question一样,我也在使用Ryan Bates的nifty_scaffold。它具有使用Mocha的any_instance方法强制隐藏在控制器后面的模型对象中的“无效”状态的理想方面。有没有办法在Test :: Unit

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

是否有一般(即:与Test :: Unit一起工作)的方式来删除any_instance存根?我相信它在我的测试中造成了一个错误,我想验证一下。

回答

31

碰巧,摩卡0.10.0允许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!" 
4

摩卡没有提供这样的功能。但是你可以自己实现它。

我们应该知道的关于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 a.a, "b" 

     A.class_eval {alias a unmocked_a} 
     assert a.a, "a" 
    end 
end 
+0

非常好。这看起来像是可以添加/ monkeypatched到摩卡的东西。 – 2010-05-24 16:05:36

+0

我从来没有觉得需要这个功能,但是如果你想游说一张票 - http://floehopper.lighthouseapp.com/projects/22289-mocha/tickets/69-allow-unstubbing-of-methods为改变。如果你有一些你为什么想要使用它的例子,那将是非常好的。 – 2010-09-26 16:51:02

+0

我已添加未分类功能 - 摩卡::对象方法#未读 - 请参阅http://mocha.rubyforge.org/classes/Mocha/ObjectMethods.html#M000009 – 2010-12-02 11:08:19

0

如果你想删除一个全力以赴的存根/预期,那么你可以做,使用mocha_teardown(如呼叫self.mocha_teardown)。

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