assert_db_rejects - Test database constraints in Ruby on Rails

Posted on 11/14/2009

If you believe in using database constraints in addition to ActiveRecord validations, you may find assert_db_rejects useful to help you test them.

require 'test_helper'

class PersonTest < ActiveSupport::TestCase

  test "database blocks duplicate names" do
    Person.create!( :name => "Test" )

    # Assume the people table has a not null constraint on name. The assertion
    # will pass if a ActiveRecord::StatementInvalid is raised when saving p.
    # Validations are bypassed by assert_db_rejects as the purpose is to test
    # the database and not the model
    assert_db_rejects( :name => "Test" ) )
blog comments powered by Disqus