是否可以在父类中存根一个方法,以便所有子类实例都在 rspec 中存根?

发布于 2024-12-06 16:43:19 字数 704 浏览 1 评论 0原文

给定一个父类 Fruit 及其子类 AppleBanana,是否可以存根 中定义的方法 foo Fruit,以便在 AppleBanana 的任何实例上对方法 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

缺⑴份安定 2024-12-13 16:43:19

这可能不是最干净的解决方案,但它有效:

Fruit.subclasses.each{|c| c.any_instance.stubs(:foo)}

This probably isn't the cleanest solution but it works:

Fruit.subclasses.each{|c| c.any_instance.stubs(:foo)}
第几種人 2024-12-13 16:43:19

更新 @weexpectedTHIS Rspec 3.6 的答案:

 Fruit.subclasses.each do |klass|
    allow_any_instance_of(klass).to receive(:foo).and_return(<return_value>)
 end

UPDATE of @weexpectedTHIS answer for Rspec 3.6:

 Fruit.subclasses.each do |klass|
    allow_any_instance_of(klass).to receive(:foo).and_return(<return_value>)
 end
我恋#小黄人 2024-12-13 16:43:19

如果你的子类还有子类,你可能必须递归地遍历它们。我做了这样的事情:

def stub_subclasses(clazz)
  clazz.any_instance.stubs(:foo).returns(false)
  clazz.subclasses.each do |c|
    stub_subclasses(c)
  end
end
stub_subclasses(Fruit)

If your subclasses have subclasses, you may have to traverse them all recursively. I did something like this:

def stub_subclasses(clazz)
  clazz.any_instance.stubs(:foo).returns(false)
  clazz.subclasses.each do |c|
    stub_subclasses(c)
  end
end
stub_subclasses(Fruit)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文