Rails ActiveSupport: How to assert that an error is raised?

Ruby on-RailsAssertActivesupportRaise

Ruby on-Rails Problem Overview

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

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?

Ruby on-Rails Solutions

Solution 1 - Ruby on-Rails

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

assert_raise(Exception) { whatever.merge }

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

lambda { whatever.merge }.should raise_error

If you want to check the raised Exception:

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

Solution 2 - Ruby on-Rails

To ensure that no exception is raised (or is successfully handled) do inside your test case:

assert_nothing_raised RuntimeError do

To check that error is raised do inside your test case:

assert_raise RuntimeError do

Just a heads up, whatever.merge is the code that raises the error (or doesn't, depending on the assertion type).


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionspillitonView Question on Stackoverflow
Solution 1 - Ruby on-RailsMatt BriggsView Answer on Stackoverflow
Solution 2 - Ruby on-RailsshivamView Answer on Stackoverflow