我想测试我的模型中一个会抛出特定错误的函数。这个函数大致如下:
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文档,但没有找到有用的信息。你有什么建议吗?
assert_raise(Exception() { whatever.merge })
,即它寻找一个名为Exception
的方法,并使用给定的块调用它。添加括号可以消除歧义。(已经修正了答案) - Daniel Rikowskiexpect { whatever.merge }.to raise_error
(http://www.relishapp.com/rspec/rspec-expectations/v/3-1/docs/built-in-matchers/raise-error-matcher) - Jared Beck