使用RSpec测试模块内部的类

Wil*_*ers 5 ruby testing rspec ruby-on-rails rspec-rails

因此,我在ruby代码中有一个看起来像这样的模块:

module MathStuff
  class Integer
    def least_factor
      # implementation code
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

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

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

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

NoMethodError:
    undefined method `least_factor' for 50:Fixnum
Run Code Online (Sandbox Code Playgroud)

如果您知道如何包含MathStuff::Integer测试类,请告诉我。

注意:为澄清起见,我实际上是在尝试在此处打开Ruby Integer类并向其中添加方法。

Mau*_*res 3

您的代码应如下所示:

describe MathStuff::Integer do
  describe '#least_factor' do
    it 'returns the least prime factor' do
      expect(MathStuff::Integer.new.least_factor).to eq 2
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

但是您正在调用50.least_factor,并且 50 是一个Fixnum对象,而不是您的对象MathStuff::Integer,并且它没有定义该方法。