ChatGPT解决这个技术问题 Extra ChatGPT

如何在任何异常情况下使用 RSpec 的 should_raise?

我想做这样的事情:

some_method.should_raise <any kind of exception, I don't care>

我该怎么做?

some_method.should_raise exception

......不起作用。


C
Community
expect { some_method }.to raise_error

RSpec 1 语法:

lambda { some_method }.should raise_error

有关更多信息,请参阅 the documentation(RSpec 1 语法)和 RSpec 2 documentation


啊..我刚刚注意到花括号!
C
Community

规格 2

expect { some_method }.to raise_error
expect { some_method }.to raise_error(SomeError)
expect { some_method }.to raise_error("oops")
expect { some_method }.to raise_error(/oops/)
expect { some_method }.to raise_error(SomeError, "oops")
expect { some_method }.to raise_error(SomeError, /oops/)
expect { some_method }.to raise_error(...){|e| expect(e.data).to eq "oops" }

# Rspec also offers to_not:
expect { some_method }.to_not raise_error
...

注意:raise_errorraise_exception 可以互换。

规格 1

lambda { some_method }.should raise_error
lambda { some_method }.should raise_error(SomeError)
lambda { some_method }.should raise_error(SomeError, "oops")
lambda { some_method }.should raise_error(SomeError, /oops/)
lambda { some_method }.should raise_error(...){|e| e.data.should == "oops" }

# Rspec also offers should_not:
lambda { some_method }.should_not raise_error
...

注意:raise_errorraise_exception 的别名。

文档:https://www.relishapp.com/rspec

规格 2:

https://www.relishapp.com/rspec/rspec-expectations/v/2-13/docs/built-in-matchers/raise-error-matcher

规格 1:

http://apidock.com/rspec/Spec/Matchers/raise_error

http://apidock.com/rspec/Spec/Matchers/raise_exception


raise_error(/oops/) 是检查异常消息中的子字符串的好方法
感谢您指出 raise_error 和 for raise_exception 是可以互换的 (y)
g
gerry3

而不是 lambda,使用 expect 来:

   expect { some_method }.to raise_error

这适用于 rspec 的更新版本,即 rspec 2.0 及更高版本。

有关更多信息,请参阅 doco


我不会将它用于 Rspec 1,但对于 Rspec 2,它可以正常工作。
实际上,根据上面的文档链接,这应该是期望 { some_method }.to raise_error
您的评论和您链接到的页面都没有解释为什么 expectlambda 更好或更差。
expect 适用于 rspec 2.0 及更高版本。这使得争论哪个更好,因为 lambda 语法不再起作用
这对我在水豚中不起作用:expect { visit welcome_path }.to raise_error
a
ayckoster

语法最近发生了变化,现在是:

expect { ... }.to raise_error(ErrorClass)

B
Bruno E.

rspec-expections 的 3.3 版开始,gem 会针对没有参数的空白 raise_error 发出警告

expect { raise StandardError }.to raise_error # results in warning
expect { raise StandardError }.to raise_error(StandardError) # fine

这给您一个提示,即您的代码可能会因与要检查的测试不同的错误而失败。

警告:在不提供特定错误或消息的情况下使用 raise_error 匹配器可能会出现误报,因为当 Ruby 引发 NoMethodError、NameError 或 ArgumentError 时,raise_error 将匹配,这可能会允许期望通过,甚至无需执行您打算调用的方法。而是考虑提供特定的错误类别或消息。可以通过设置来抑制此消息:RSpec::Expectations.configuration.warn_about_potential_false_positives = false。