我似乎无法找到一个看似简单的谷歌搜索。
我的程序中有一个rspecit "fails informatively when there's not enough values stacked away" do
expect {
calculator.plus
}.to raise_error("calculator is empty")
我编写的RPN计算器程序中plus方法的代码是:
def plus
if @calculator.length == 0
raise ArgumentError.new("calculator is empty")
end
sum = @calculator[-1] + @calculator[-2]
2.times {@calculator.pop}
@calculator.push(sum)
end
但它没有解决任何问题。我对编程非常陌生,特别是在例外方面,所以我们非常感谢任何帮助。
我确信它真的很简单,但我已经被困在这一小时超过一个小时了。
这是我运行捆绑包rspec时收到的错误消息:
F Failure/Error: expect { expected Exception with "calculator is empty", got # with backtrace: # ./lib/12_rpn_calculator.rb:22:in `minus' # ./spec/12_rpn_calculator_spec.rb:124:in `block (3 levels) in ' # ./spec/12_rpn_calculator_spec.rb:123:in `block (2 levels) in '
答案 0 :(得分:0)
假设您希望应用程序代码保持不变,则应该可以使用以下任意一种代码:
it "fails informatively when there's not enough values stacked away" do
expect { calculator.plus }.to raise_error(/calculator is empty/)
expect { calculator.plus }.to raise_error(ArgumentError, "calculator is empty")
expect { calculator.plus }.to raise_error(ArgumentError, /calculator is empty/)
end
https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/raise-error-matcher
答案 1 :(得分:-2)
我写的如下。我在解决这个测试时失败了很多。
def times
n1=@calculator.pop
n2=@calculator.pop
if n1==nil || n2==nil
raise('calculator is empty')
else
@calculator.push(n2.to_f*n1.to_f)
end
end