【问题标题】:Ruby: rspec not catching exceptions?Ruby:rspec 没有捕获异常?
【发布时间】: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


【解决方案1】:

你需要存根 add 方法而不是 calculate 并且你需要引发异常而不是返回异常。

describe "sample" do
  it "adds numbers" do
    test = Sample.new

    allow(test)
      .to receive(:add)
      .with(1, 2).and_raise(Exception.new('foo'))

    expect(test.calculate(1,2)). to eq 'Exception occurred: foo'
  end
end

【讨论】:

  • 嗯,这会导致同样的错误吗? ruby Failure/Error: expect(test.calculate(1,2)). to eq 'Exception occurred: foo' expected: "Exception occurred: foo" got: #&lt;Exception: foo&gt; (compared using ==)
  • @no_onespecial 我已经更新了答案。你现在可以检查一下吗?
  • 另外calculate方法中有错别字,occured改成occurred
猜你喜欢
  • 1970-01-01
  • 2013-03-24
  • 2013-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
  • 2013-08-08
相关资源
最近更新 更多