Validation Assertions
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
endclass 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
endThat’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/
XML Validation Plugin
I’ve written a new Rails plugin to validate xml.
class Article < ActiveRecord::Base
validates_xml :body
endArticle.new(:body => "<span>This will fail").save!ActiveRecord::RecordInvalid: Validation failed: Body is not valid xml
Get it here: https://secure.near-time.com/svn/plugins/trunk/validates_xml
Rails validates_presence_of Strangeness
I found an annoying bug in validates_presence_of, it does not like booleans.
class CreateNodes < ActiveRecord::Migration
def self.up
create_table :nodes do |t|
t.column :boolean_var, :boolean, :default => 0
end
end
endclass Node < ActiveRecord::Base
validates_presence_of :boolean_var
endclass NodeTest < Test::Unit::TestCase
def test_boolean_var
node = Node.new
node.boolean_var = 0
node.save!
end
end 1) Error:
test_boolean_var(NodeTest):
ActiveRecord::RecordInvalid: Validation failed: Boolean var can't be blank
/opt/local/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/active_record/validations.rb:736:in
`save!'
/Users/jwulff/Development/NodeTestApp/test/unit/node_test.rb:5:in
`test_boolean_var'
1 tests, 0 assertions, 0 failures, 1 errorsBlake Watters gave me this workaround.
validates_inclusion_of :boolean_var, :in => [true, false]I’ve opened a ticket at dev.rubyonrails.org
UPDATE: The ticket has been closed as invalid. Manfred says:
validates_presence_of behaves exactly as documented. Please use {{{validates_inclusion_of :boolean_var, :in => [true, false]}} as the first commenter suggested.