我想做这样的事情:
some_method.should_raise <any kind of exception, I don't care>
我该怎么做?
some_method.should_raise exception
......不起作用。
expect { some_method }.to raise_error
RSpec 1 语法:
lambda { some_method }.should raise_error
有关更多信息,请参阅 the documentation(RSpec 1 语法)和 RSpec 2 documentation。
规格 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_error
和 raise_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_error
是 raise_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
而不是 lambda,使用 expect 来:
expect { some_method }.to raise_error
这适用于 rspec 的更新版本,即 rspec 2.0 及更高版本。
有关更多信息,请参阅 doco。
expect
比 lambda
更好或更差。
expect { visit welcome_path }.to raise_error
语法最近发生了变化,现在是:
expect { ... }.to raise_error(ErrorClass)
从 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。
不定期副业成功案例分享