Rspec 提高匹配器不工作,从文档中复制语法?

Rspec raise matcher not working, copied syntax from docs?

rspec-core (3.9.1)
rspec-expectations (3.9.0)
rspec-mocks (3.9.1)
rspec-rails (4.0.0.beta4, 3.9.0)
rspec-support (3.9.2)

根据文档:https://relishapp.com/rspec/rspec-expectations/v/3-9/docs/built-in-matchers/raise-error-matcher,这应该有效:

expect { raise StandardError }.to raise_error

然而在我的代码中,当我 运行 只是那个规范本身时,我得到:

Failures:

  1) time rules should work
     Failure/Error: expect(raise StandardError).to raise_error
     
     StandardError:
       StandardError
     # ./spec/models/time_rules_spec.rb:87:in `block (2 levels) in <top (required)>'

仔细看错误:

Failure/Error: expect(raise StandardError).to raise_error

这表明您的失败测试如下所示:

it '...' do
  expect(raise StandardError).to raise_error
end

什么时候应该是这样的:

it '...' do
  expect { raise StandardError }.to raise_error
end

您的版本相当于:

result = raise StandardError
expect(result).to raise_error

所以 raiseraise_error 可以捕获并检查异常之前被触发。如果像文档中那样将块传递给 expect

expect { raise StandardError }.to raise_error

然后 raise_error 匹配器将设置所有内容以捕获和检查异常。


顺便说一句,您可能希望更明确地使用 raise_error 匹配器:

expect { raise StandardError }.to raise_error(StandardError)

避免过于宽泛的匹配器和这样的警告:

WARNING: Using the raise_error matcher without providing a specific error or message risks false positives, since raise_error will match when Ruby raises a NoMethodError, NameError or ArgumentError, potentially allowing the expectation to pass without even executing the method you are intending to call.