Search code examples
rubyunit-testingtestunitshouldapadrino

How to test for exceptions in shoulda along with TestUnit?


I have an application based on padrinorb and I am using the shoulda testing library for the same. There is a method that I need to test throws exception. I tried finding the documentation for the same, but couldn't find anything.

Here's the sample code that I want to test

def some_method(param)
    raise APIException.new('Exception) if param == 2
end

How should I test that the some_method throws an exception when passed the parameter 2.


Solution

  • expect{ some_method(params) }.to raise_error(APIException)
    

    if you use TestUnit this should work (source)

    assert_raises(APIException) { some_method(params) }
    

    To test the exception message as well use the following:

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