本文介绍了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:如何断言发生错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 02:45