2013-02-27 29 views
0

我想在多個操作系統中測試一個類方法的行爲,而不必實際運行它們上的代碼。我使用的是OS Rubygem如何在RSpec中存根外部ruby gem的方法?

我想測試3例此功能在RSpec中:

def get_os() 
    if OS.linux? 
     return "linux#{OS.bits}" 
    elsif OS.mac? 
     return "mac" 
    elsif OS.doze? 
     return "win" 
    end 

我創建了一個簡單的測試項目here

你可以用這條命令:

git clone git://github.com/trinitronx/rspec-stubmock-test.git 
cd rspec-stubmock-test/ 
bundle install 
rspec 

我嘗試手動覆蓋OS.*?方法,但它似乎並沒有工作。我怎樣才能做到這一點?

回答

3

你就應該能夠存根這樣的方法:

describe "#get_os" do 

    subject { TestMe.new.get_os } 

    context "on a linux machine" do 

    before do 
     OS.stub(linux?: true, mac?: false, doze?: false, bits: 64) 
    end 

    it { should eq 'linux64' } 
    end 

    context "on a mac" do 

    before do 
     OS.stub(linux?: false, mac?: true, doze?: false, bits: 64) 
    end 

    it { should eq 'mac' } 
    end 

    # etc etc 
end 
+0

謝謝!這按預期工作^ _ ^ – TrinitronX 2013-02-27 20:16:46