【问题标题】:Answering rspec to raise_error in Ruby在 Ruby 中回答 rspec 到 raise_error
【发布时间】:2016-11-11 04:49:34
【问题描述】:

基本上,我正在尝试回答一系列 Rspec 指令。其中一条指令是这样的:

it "fails informatively when there's not enough values stacked away" do
  expect {
     calculator.plus
  }.to raise_error("calculator is empty")
end

所以我了解了 raise_error 以及如何回答它,是我创建了某种错误/异常。

def plus
  @array_nums.length >= 2 ? @array_nums << @array_nums.pop + @array_nums.pop : raise {"calculator is empty"}
  @value = @array_nums[-1]

要清楚,底部有一个结束,但文本编辑器没有处理它。所以我提出了错误,我试图提出 ArgumentError 和所有这些,但我不断从 rspec 得到这个响应:

Failure/Error:
   expect {
     calculator.plus
   }.to raise_error("calculator is empty")

   expected Exception with "calculator is empty", got RuntimeError with backtrace:
     # ./lib/12_rpn_calculator.rb:16:in `plus'
     # ./spec/12_rpn_calculator_spec.rb:119:in `block (3 levels) in <top (required)>'
     # ./spec/12_rpn_calculator_spec.rb:118:in `block (2 levels) in <top (required)>'
 # ./spec/12_rpn_calculator_spec.rb:118:in `block (2 levels) in <top (required)>'

我尝试的任何其他错误都不起作用,我正在努力寻找正确的方向来解决这个问题。也许我找错地方了?感谢您的帮助,谢谢!

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

    试试这个:

      @array_nums.length >= 2 ? @array_nums << @array_nums.pop + @array_nums.pop : raise StandardError, 'calculator is empty'
    

    【讨论】:

    • 试过这个:这是我得到的错误 - /usr/local/rvm/gems/ruby-2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1435:in `load': /home/ubuntu/workspace/test-first-ruby-master/lib/12_rpn_calculator.rb:16: syntax error, unexpected tCONSTANT, expecting keyword_do or '{' or '(' (SyntaxError) ..._nums.pop : raise StandardError, 'calculator is empty
    • 也包括/home/ubuntu/workspace/test-first-ruby-master/lib/12_rpn_calculator.rb:16: dynamic constant assignment ...nums.pop : raise StandardError, 'calculator is empty'
    • 可能是三元的原因,试试把 raise params 包在 parens 里
    • 顺便感谢您的帮助。仍然是同样的错误,除了括号我只得到第一个错误而不是第二个。
    • @BrandonThaler Ruby 错误消息通常会告诉您错误发生的确切位置(在这种情况下,在文件 12_rpn_cal‌​culator.rb 的行 16 中)。在不知道该文件的外观的情况下,没有人可以帮助您解决这个问题——尤其是在第 16 行附近。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多