Rails ActiveSupport:如何断言引发错误?
我想在我的模型之一上测试一个引发特定错误的函数。该函数看起来像这样:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
所以单元测试并没有得到真正的积极支持。 Ruby 在标准库中附带了一个典型的 xunit 框架(ruby 1.8.x 中的 Test::Unit,ruby 1.9 中的 MiniTest),而 activesupport 中的内容只是向其中添加了一些内容。
如果您正在使用 Test::Unit/MiniTest
如果您正在使用 rspec(不幸的是,文档记录很少,但更流行)
如果您想检查引发的
异常
: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
if you are using rspec (unfortunately poorly documented, but way more popular)
If you want to check the raised
Exception
:为了确保不会引发异常(或成功处理),请在测试用例中执行以下操作:
要检查是否引发错误,请在测试用例中执行以下操作:
请注意,
whatever.merge
是以下代码:引发错误(或不引发错误,具体取决于断言类型)。To ensure that no exception is raised (or is successfully handled) do inside your test case:
To check that error is raised do inside your test case:
Just a heads up,
whatever.merge
is the code that raises the error (or doesn't, depending on the assertion type).