【发布时间】:2021-06-20 17:48:13
【问题描述】:
我无法理解 rspec 如何处理异常。在这种情况下,我想确保异常被正确捕获并以格式化消息的形式返回。
考虑以下几点:
class Sample
def calculate(x, y)
begin
add(x,y)
rescue Exception => e
return "Exception occured: #{e}"
end
end
def add(x, y)
x + y
end
end
有这样的规范:
describe "sample" do
it "adds numbers" do
test = Sample.new
allow(test)
.to receive(:calculate)
.with(1, 2) { Exception.new('foo') }
expect(test.calculate(1,2)). to eq 'Exception occurred: foo'
end
end
我希望异常被 rspec 正确捕获,因为它是由方法 calculate 本身,但是,我在执行规范时收到以下内容:
Failures:
1) sample adds numbers
Failure/Error: expect(test.calculate(1,2)). to eq 'Exception occurred: foo'
expected: "Exception occurred: foo"
got: #<Exception: foo>
(compared using ==)
Diff:
@@ -1,2 +1,2 @@
-"Exception occurred: foo"
+#<Exception: foo>
但是通过irb测试救援时,处理得当:
irb(main):001:0> test = Sample.new()
=> #<Sample:0x000055d0f864db50>
irb(main):002:0> test.calculate("i", 2)
=> "Exception occured: no implicit conversion of Integer into String"
irb(main):003:0>
我对 rspec 很陌生,所以欢迎任何反馈:D
【问题讨论】:
-
allow(test) .to receive(:add) .with(1, 2) .and_raise(Exception.new('foo'))
-
@LamPhan 这会导致来自 rspec 的相同输出
-
请检查您是否存根
:add方法以引发错误(通知and_raise),我在我这边检查过,它工作正常。
标签: ruby unit-testing testing rspec