2013-02-27 27 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