Rails ActiveSupport:如何断言引发错误?

发布于 2024-09-13 23:44:26 字数 402 浏览 2 评论 0原文

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

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

久夏青 2024-09-20 23:44:26

所以单元测试并没有得到真正的积极支持。 Ruby 在标准库中附带了一个典型的 xunit 框架(ruby 1.8.x 中的 Test::Unit,ruby 1.9 中的 MiniTest),而 activesupport 中的内容只是向其中添加了一些内容。

如果您正在使用 Test::Unit/MiniTest

assert_raise(Exception) { whatever.merge }

如果您正在使用 rspec(不幸的是,文档记录很少,但更流行)

lambda { whatever.merge }.should raise_error

如果您想检查引发的异常

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

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.

If you are using Test::Unit/MiniTest

assert_raise(Exception) { whatever.merge }

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

lambda { whatever.merge }.should raise_error

If you want to check the raised Exception:

exception = assert_raises(Exception) { whatever.merge }
assert_equal( "message", exception.message )
偷得浮生 2024-09-20 23:44:26

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

assert_nothing_raised RuntimeError do
  whatever.merge
end

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

assert_raise RuntimeError do
  whatever.merge
end

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

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.merge is the code that raises the error (or doesn't, depending on the assertion type).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文