使用 RSpec 测试模块内的类 [英] Testing a Class inside of a Module with RSpec

查看:30
本文介绍了使用 RSpec 测试模块内的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我的 ruby​​ 代码中有一个模块,如下所示:

So, I have a module in my ruby code which looks something like this:

module MathStuff
  class Integer
    def least_factor
      # implementation code
    end
  end
end

并且我有一些 RSpec 测试,我想在其中测试我的 Integer#least_factor 方法是否按预期工作.为简单起见,我们会说测试在同一个文件中.测试看起来像这样:

and I have some RSpec tests in which I would like to test that my Integer#least_factor method works as expected. we'll say that the tests are in the same file for simplicity. The tests look something like this:

describe MathStuff do
  describe '#least_factor' do
    it 'returns the least prime factor' do
      expect(50.least_factor).to eq 2
    end
  end
end

不幸的是,当我运行测试时,出现如下错误:

Unfortunately, when I run the tests, I get an error like this:

NoMethodError:
    undefined method `least_factor' for 50:Fixnum

如果您知道如何包含用于测试的 MathStuff::Integer 类,请告诉我.

Please let me know if you know how to include the MathStuff::Integer class for testing.

注意:为了澄清起见,我实际上是在尝试在这里打开 Ruby Integer 类并向其添加方法.

Note: just for clarification, I am actually trying to open up the Ruby Integer class here and add methods to it.

推荐答案

添加之前 改进(以及 2.0 中的实验支持),您不能将这样的猴子补丁的范围限制在特定的上下文中(即一个模块).

Before the addition of refinements in Ruby 2.1 (and experimental support in 2.0), you couldn't limit the scope of a monkeypatch like this to a particular context (i.e. a module).

但是您的示例不起作用的原因是在 Mathstuff 模块下定义一个 Integer 类会创建一个与 Integer 核心类无关的新类.覆盖核心类的唯一方法是在顶层(不在模块内)打开类.

But the reason your example doesn't work is that defining an Integer class under the Mathstuff module creates a new class which has nothing to do with the Integer core class. The only way to override the core class is to open the class at the top level (not within a module).

我通常将核心扩展放在 lib/core_ext 子目录中,以它们正在修补的类命名,在你的例子中是 lib/core_ext/integer.rb.

I usually put core extensions in a lib/core_ext subdirectory, named after the class they are patching, in your case lib/core_ext/integer.rb.

这篇关于使用 RSpec 测试模块内的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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