如何在RSpec中存储外部ruby gem的方法?

时间:2022-10-30 08:09:14

I'm trying to test a class method's behavior in multiple operating systems, without actually having to run the code on them. I'm using the OS Rubygem

我试图在多个操作系统中测试类方法的行为,而不必实际运行代码。我正在使用操作系统Rubygem

I want to test the 3 cases of this function in RSpec:

我想在RSpec中测试这个函数的3个案例:

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

I've created a quick test project here

我在这里创建了一个快速测试项目

You can run this with:

您可以使用以下命令运行:

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

I tried manually overriding the OS.*? methods, but it doesn't seem to work. How can I do this?

我试着手动覆盖操作系统。*?方法,但似乎没有用。我怎样才能做到这一点?

1 个解决方案

#1


3  

You should just be able to stub the methods like this:

你应该只能存储这样的方法:

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

#1


3  

You should just be able to stub the methods like this:

你应该只能存储这样的方法:

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