如何使用rspec在ruby中模拟super?
我通过创建一个扩展到库类的子类来扩展现有的库。
在子类中,我能够在initialize
方法中测试大多数function,但无法模拟super
调用。 子类看起来像下面的东西。
class Child < SomeLibrary def initialize(arg) validate_arg(arg) do_something super(arg) end def validate_arg(arg) # do the validation end def do_something @setup = true end end
如何编写rspec测试(使用mocha)以便我可以模拟super
调用? 请注意,我正在测试Child
类中initialize
方法的function。 我是否必须创建单独的代码路径,在提供额外参数时不会调用super
?
你不能嘲笑super
,你不应该。 当你模拟某些东西时,你正在validation是否收到了一条特定的消息,而super
则不是一条消息 – 它是一个关键字。
相反,要弄清楚如果缺少super
调用,这个类的行为会发生什么变化,并编写一个练习并validation该行为的示例。
测试这个的一个好方法是设置超类采取某些操作的期望 – 例如:
class Some::Thing < Some def instance_method super end end
和超级class:
class Some def instance_method another_method end def self.another_method # not private! 'does a thing' end end
现在测试:
describe '#instance_method' do it 'appropriately triggers the super class method' do sawm = Some::Thing.new expect(sawm).to receive(:another_method) sawm.instance_method end end
所有这一切都决定了超级类的超级调用
这种模式的有用性取决于您如何构建测试/通过应用的super
方法对子/衍生类突变的期望。
另外 - 密切关注class
和instance
方法,您需要相应地调整allows
和expects
因人而异