Rails ActiveSupport:如何断言出现错误? [英] Rails ActiveSupport: How to assert that an error is raised?

查看:33
本文介绍了Rails 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

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

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 中.Ruby 在标准库中带有一个典型的 xunit 框架(ruby 1.8.x 中的 Test::Unit,ruby 1.9 中的 MiniTest),而 activesupport 中的东西只是添加了一些东西.

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.

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

If you are using Test::Unit/MiniTest

assert_raise(Exception) { whatever.merge }

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

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

lambda { whatever.merge }.should raise_error

如果你想检查引发的Exception:

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

这篇关于Rails ActiveSupport:如何断言出现错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆