如何使用 rspec 在 ruby​​ 中模拟 super ? [英] How can I mock super in ruby using rspec?

查看:42
本文介绍了如何使用 rspec 在 ruby​​ 中模拟 super ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过创建一个扩展到库类的子类来扩展现有的库.

I am extending an existing library by creating a child class which extends to the library class.

在子类中,我能够测试initialize 方法中的大部分功能,但无法模拟super 调用.子类看起来像下面这样.

In the child class, I was able to test most of functionality in initialize method, but was not able to mock super call. The child class looks like something like below.

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 方法的功能.当提供额外参数时,我是否必须创建不调用 super 的单独代码路径?

How can I write rspec test (with mocha) such that I can mock super call? Note that I am testing functionality of initialize method in the Child class. Do I have to create separate code path which does not call super when it is provided with extra argument?

推荐答案

你不能模拟 super,你也不应该.当您模拟某些内容时,您正在验证是否收到了特定的消息,并且 super 不是消息——它是一个关键字.

You can't mock super, and you shouldn't. When you mock something, you are verifying that a particular message is received, and super is not a message -- it's a keyword.

相反,弄清楚如果 super 调用丢失,这个类的行为会发生什么变化,并编写一个例子来练习和验证该行为.

Instead, figure out what behavior of this class will change if the super call is missing, and write an example that exercises and verifies that behavior.

这篇关于如何使用 rspec 在 ruby​​ 中模拟 super ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆