Testing exceptions in Rails

written by edavis on July 6th, 2007 @ 04:35 PM

If you want to make sure an exception is thrown in a Rails test just use the assert_raise assertion. For example, I am testing to make sure the SQL statement is invalid after it goes through my model’s validation

def test_exception
    c = Content.new
    # Title is missing
    assert_raise ActiveRecord::StatementInvalid do
      c.save
    end
end

This snippet is looking for the ActiveRecord::StatementInvalid exception when it calls the c.save method.

Eric Davis

Comments

  • Endy on July 13, 2007 @ 05:19 AM

    We should test everything, because 30% of all proframs need to be done by ourselves, but then we're learning ;)

  • Simon on August 02, 2007 @ 04:19 AM

    Yeah, that's really very simple and nice testing stuff. I always use it...

Post a comment