2013-10-06 159 views
4

所以,我在我的Ruby代碼的模塊,看起來是這樣的:測試一類模塊內使用RSpec

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

和我有一些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 

不幸的是,當我運行測試,我得到這樣一個錯誤:

NoMethodError: 
    undefined method `least_factor' for 50:Fixnum 

請讓我知道,如果你知道如何包括MathStuff::Integer類測試。

注意:爲了澄清,我實際上試圖在這裏打開Ruby Integer類並向其添加方法。

回答

1

您的代碼應該是這樣的:

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 

但你打電話50.least_factor和50是Fixnum對象,而不是你的MathStuff::Integer,它不具有已定義的方法。

+0

所以,如果我'MathStuff :: Integer.new(50).least_factor'我得到一個參數錯誤,說'#新'採用零參數。我應該如何將值設置爲50? –

0

簡單,但不推薦方式:

require "rspec" 

class Integer 
    def plus_one 
    self + 1 
    end 
end 

describe 'MathStuff' do 
    describe '#plus_one' do 
    it 'should be' do 
     expect(50.plus_one).to eq 51 
    end 
    end 
end 

$ rspec test.rb 
. 

Finished in 0.01562 seconds 
1 example, 0 failures 
+0

這樣做的唯一問題是模塊中不包含對整數類的添加。 –

3

用Ruby 2.1(和2.0的實驗性支持)添加refinements之前,你不能像這樣的猴補丁的範圍限制在一個特定的上下文(即模塊)。

但是你的例子不起作用的原因是,在Mathstuff模塊下定義一個Integer類會創建一個新的類,它與Integer核心類無關。覆蓋核心類的唯一方法是打開頂層的類(不在模塊內)。

我通常把核心擴展名放在一個lib/core_ext子目錄中,以他們正在修補的類的名字命名,在你的例子中是lib/core_ext/integer.rb。