Validation Assertions

Posted by John Wulff Tue, 26 Jun 2007 19:06:00 GMT

I like to test my validations. While I don’t really care to test the underlying code that runs the validations (I trust the Rails team to make sure they work as advertised) I do like the reassurance that I didn’t screw up. So, I’ve written this small plugin to help me test my validations.

It works simply. In one of your models you’ve got a validation like this:
class User < ActiveRecord::Base
  validates_presence_of :name
  validates_length_of :name, :in => 4..26
  validates_uniqueness_of :name
end
To test the validations:
class UserTest < Test::Unit::TestCase  
  # Assert that a User's name must exist for validations to pass.
  def test_validates_presence_of_name
    assert_validates_presence_of User, :name
  end

  # Assert that a User's name must be at least 4 characters in length for
  # validations to pass.
  def test_validates_minimium_length_of_name
    assert_validates_minimum_length_of User, :name, 4
  end

  # Assert that a User's name must be less than 26 characters in length for
  # validations to pass.
  def test_validates_maximum_length_of_name
    assert_validates_maximum_length_of User, :name, 26
  end

  # Assert that a User's name must be unique for validations to pass.
  def test_validates_uniqueness_of_name
    assert_validates_uniqueness_of User, :name
  end
end

That’s it. Now you can rest easy know that your validations are really, really, really in place.

To install the plugin:
script/plugin install http://validation-assertions.googlecode.com/svn/trunk/validation_assertions/

Google Code Project Page

Trackbacks

Use the following link to trackback from your own site:
http://www.johnwulff.com/trackbacks?article_id=21

Leave a comment

Comments