Testing exceptions in Rails

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

2 comments

  1. Endy says:

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

Comments are closed.