为错误条件编写 Rspec 测试并退出

Writing a Rspec test for an error condition finished with exit

我正在为 Ruby gem 编写一个命令行界面,我有这个方法 exit_error,它作为处理时执行的所有验证的退出错误点。

def self.exit_error(code,possibilities=[])
  puts @errormsgs[code].colorize(:light_red)
  if not possibilities.empty? then
    puts "It should be:"
    possibilities.each{ |p| puts "  #{p}".colorize(:light_green) }
  end
  exit code
end

其中 @errormsgs 是一个散列,其键是错误代码,其值是相应的错误消息。

通过这种方式,我可以为用户提供自定义的错误消息,编写如下验证:

exit_error(101,@commands) if not valid_command? command

其中:

@errormsgs[101] => "Invalid command." 
@commands = [ :create, :remove, :list ] 

并且输入错误命令的用户会收到如下错误消息:

Invalid command.
It should be:
  create
  remove
  list

同时,这样我可能会有 bash 脚本准确检测导致退出条件的错误代码,这对我的 gem.

非常重要

使用此方法和整个策略一切正常。但我必须承认,我没有先写测试就写了这一切。我知道,我知道...我真丢人!

现在我已经完成了 gem,我想提高我的代码覆盖率。其他一切都由书本完成,先编写测试,然后再编写代码。因此,最好也对这些错误条件进行测试。

当我使用 exit 中断处理时,碰巧我真的不知道如何针对这种特殊情况编写 Rspec 测试。有什么建议吗?

更新 => 这个gem 是"programming environment" 的一部分,里面有很多bash 脚本。其中一些脚本需要确切地知道中断命令执行的错误情况才能采取相应的行动。

例如:

class MyClass
  def self.exit_error(code,possibilities=[])
    puts @errormsgs[code].colorize(:light_red)
    if not possibilities.empty? then
      puts "It should be:"
      possibilities.each{ |p| puts "  #{p}".colorize(:light_green) }
    end
    exit code
  end
end

你可以把它的 rspec 写成这样:

describe 'exit_error' do
  let(:errormsgs) { {101: "Invalid command."} }
  let(:commands) { [ :create, :remove, :list ] }
  context 'exit with success'
    before(:each) do
      MyClass.errormsgs = errormsgs # example/assuming that you can @errormsgs of the object/class
      allow(MyClass).to receive(:exit).with(:some_code).and_return(true)
    end

    it 'should print commands of failures'
      expect(MyClass).to receive(:puts).with(errormsgs[101])
      expect(MyClass).to receive(:puts).with("It should be:")
      expect(MyClass).to receive(:puts).with(" create")
      expect(MyClass).to receive(:puts).with(" remove")
      expect(MyClass).to receive(:puts).with(" list")
      MyClass.exit_error(101, commands)
    end
  end

  context 'exit with failure'
    before(:each) do
      MyClass.errormsgs = {} # example/assuming that you can @errormsgs of the object/class
      allow(MyClass).to receive(:exit).with(:some_code).and_return(false)
    end

    # follow the same approach as above for a failure
  end
end

当然,这是您的规范的初始前提,如果您复制并粘贴代码可能无法正常工作。为了从 rspec.

获得绿色信号,您将不得不做一些阅读和重构