Validation assertion added to test_spec_on_rails

I’ve added a new assertion to test_spec_on_rails that enables verification that validates_presence_of is being called correctly on your ActiveRecord models. For example, say you have a model like this:

class User < ActiveRecord::Base
  validates_presence_of :first_name, :last_name
end

You would typically test this validation by leaving a field blank, calling valid? or save on the instance, and checking the errors collection for messages:

describe "User" do
  it "should validate presence of first name" do
    user = User.new(:first_name => nil)
    user.valid?
    user.errors.on(:first_name).should == "can't be blank"
  end
end

Aside from being tedious to write, this method of testing isn't very fast. With the latest version of test_spec_on_rails your test becomes:

describe "User" do
  it_should_validate_presence_of :first_name, :last_name
end

Nice, simple... and fast. Behind the scenes, validation reflection is being used to ensure that validates_presence_of is being called on the model class. The model itself is never instantiated which speeds things up. The test itself is also very clean and easy to read. (You can't get much cleaner than a single line of code, right?)

What about verifying options that are passed to the validation? This new enhancement handles that too:

class User < ActiveRecord::Base
  validates_presence_of :ssn, :if => :ssn_required?
end

describe "User" do
  it_should_validate_presence_of :ssn, :if => :ssn_required?
end

If the options passed to the assertion aren't used on the actual validation then the test will fail.

Ready to start rolling with this new hotness? test_spec_on_rails is now on Git so unless you're running Edge Rails you can't use script/install to grab it. My suggestion is to clone from Git into vendor/plugins and then svn:ignore the .git file:

git clone git://github.com/pelargir/test_spec_on_rails.git vendor/plugins/test_spec_on_rails
svn propset svn:ignore .git vendor/plugins/test_spec_on_rails