是否可以在父类中存根一个方法,以便所有子类实例都在 rspec 中存根?
给定一个父类 Fruit
及其子类 Apple
和 Banana
,是否可以存根 中定义的方法 foo
Fruit
,以便在 Apple
和 Banana
的任何实例上对方法 foo
的任何调用都被存根?
class Fruit
def foo
puts "some magic in Fruit"
end
end
class Banana < Fruit
...
end
class Apple < Fruit
...
end
Fruit.any_instance.stubs(:foo)
不起作用,看起来它只是 Fruit 实例的存根。除了为每个子类调用存根之外,是否有一种简单的方法可以实现此目的?
发现此链接提出了类似的问题,但似乎尚未得到解答。 http://groups.google.com/group/mocha-developer/browse_thread/thread/99981af7c86dad5e< /a>
Given a parent class Fruit
and its subclasses Apple
and Banana
, is it possible to stub the method foo
defined in Fruit
, so that any calls to method foo
on any instances of Apple
and Banana
are stubbed?
class Fruit
def foo
puts "some magic in Fruit"
end
end
class Banana < Fruit
...
end
class Apple < Fruit
...
end
Fruit.any_instance.stubs(:foo)
did not work and it looks like it only stubs for instances of Fruit. Is there a simple way to achieve this other than calling stubs for every subclasses?
Found this link raising the similar question but it looks like it has not been answered yet.
http://groups.google.com/group/mocha-developer/browse_thread/thread/99981af7c86dad5e
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这可能不是最干净的解决方案,但它有效:
This probably isn't the cleanest solution but it works:
更新 @weexpectedTHIS Rspec 3.6 的答案:
UPDATE of @weexpectedTHIS answer for Rspec 3.6:
如果你的子类还有子类,你可能必须递归地遍历它们。我做了这样的事情:
If your subclasses have subclasses, you may have to traverse them all recursively. I did something like this: