rspec测试控制台命令输出

时间:2018-03-24 09:26:05

标签: rspec sh fastlane

我在ruby中有以下代码段

lizard_cli_version = Gem::Version.new(`lizard --version`.scan(/(?:\d+\.?){3}/).first)
required_version = Gem::Version.new(Fastlane::Lizard::CLI_VERSION)
if lizard_cli_version < required_version
  UI.user_error!("Your lizard version is outdated, please upgrade to at least version #{Fastlane::Sentry::CLI_VERSION} and start your lane again!")
end

我想使用以下RSpec测试它,但它无法正常工作

context "there is no lizard installed" do
  it "states lizard is needed and how to install" do
    allow(FastlaneCore::UI).to receive(:user_error)
    expect(FastlaneCore::UI).to receive(:user_error).with(/Your lizard version is outdated/)

    expect(Fastlane::Actions).to receive(:sh).and_raise("1.14.1")
    expect(FastlaneCore::UI).to receive(:user_error!)

    expect do
      Fastlane::FastFile.new.parse("lane :test do
        lizard
      end").runner.execute(:test)
    end.to raise_error(/Your lizard version is outdated/)
  end
end

这是输出

Failures:

  1) Fastlane::Actions::LizardAction Lizard there is no lizard installed states lizard is needed and how to install
     Failure/Error: expect(FastlaneCore::UI).to receive(:user_error).with(/You have to install lizard using/)

       (FastlaneCore::UI (class)).user_error(/Your lizard version is outdated/)
           expected: 1 time with arguments: (/Your lizard version is outdated/)
           received: 0 times
     # ./spec/lizard_spec.rb:15:in `block (4 levels) in <top (required)>'

Finished in 1.48 seconds (files took 3.55 seconds to load)
17 examples, 1 failure

有人有任何建议如何使这项工作?

1 个答案:

答案 0 :(得分:2)

通过这些信息来判断问题并不容易,但也许这可能就是这一行......

expect(Fastlane::Actions).to receive(:sh).and_raise("1.14.1")

也许你想要的是使用and_return代替and_raise ...

expect(Fastlane::Actions).to receive(:sh).and_return("1.14.1")

在您的代码中使用Fastlane::Actions.sh获取lizard --version ...

Gem::Version.new(Fastlane::Actions.sh("lizard --version").scan(/(?:\d+\.?){3}/).first)