Ruby-on-rails Rails ActiveSupport:如何断言出现错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3454925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:01:17  来源:igfitidea点击:

Rails ActiveSupport: How to assert that an error is raised?

ruby-on-railsassertactivesupportraise

提问by spilliton

I am wanting to test a function on one of my models that throws specific errors. The function looks something like this:

我想在我的一个模型上测试一个抛出特定错误的函数。该函数看起来像这样:

def merge(release_to_delete)
  raise "Can't merge a release with itself!" if( self.id == release_to_delete.id )
  raise "Can only merge releases by the same artist" if( self.artist != release_to_delete.artist   )
  #actual merge code here
end

Now I want to do an assert that when I call this function with a parameter that causes each of those exceptions, that the exceptions actually get thrown. I was looking at ActiveSupport documentation, but I wasn't finding anything promising. Any ideas?

现在我想做一个断言,当我使用导致每个异常的参数调用此函数时,异常实际上会被抛出。我正在查看 ActiveSupport 文档,但没有发现任何有希望的东西。有任何想法吗?

回答by Matt Briggs

So unit testing isn't really in activesupport. Ruby comes with a typical xunit framework in the standard libs (Test::Unit in ruby 1.8.x, MiniTest in ruby 1.9), and the stuff in activesupport just adds some stuff to it.

所以单元测试并不是真的在 activesupport 中。Ruby 在标准库中带有一个典型的 xunit 框架(ruby 1.8.x 中的 Test::Unit,ruby 1.9 中的 MiniTest),而 activesupport 中的东西只是向其中添加了一些东西。

If you are using Test::Unit/MiniTest

如果您使用的是 Test::Unit/MiniTest

assert_raise(Exception) { whatever.merge }

if you are using rspec (unfortunately poorly documented, but way more popular)

如果您使用的是 rspec (不幸的是文档不足,但更受欢迎)

lambda { whatever.merge }.should raise_error

If you want to checkthe raised Exception:

如果要检查凸起Exception

exception = assert_raises(Exception) { whatever.merge }
assert_equal( "message", exception.message )

回答by shivam

To ensure that no exception is raised (or is successfully handled) do inside your test case:

为确保不会引发(或成功处理)异常,请在您的测试用例中执行以下操作:

assert_nothing_raised RuntimeError do
  whatever.merge
end

To check that error is raised do inside your test case:

要检查是否引发了错误,请在您的测试用例中执行以下操作:

assert_raise RuntimeError do
  whatever.merge
end

Just a heads up, whatever.mergeis the code that raises the error (or doesn't, depending on the assertion type).

请注意,whatever.merge是引发错误的代码(或不引发错误,取决于断言类型)。