Quick testing of ActiveRecord validations in RSpec

ActiveRecord’s validations are a convenient way to test and control the state of objects before they hit the database.

Validations are themselves a presumably well-tested part of Ruby on Rails, but their usage in an application significantly changes the behaviour of your objects.

This means their usage should be spec’d like anything else.

Spec’ing out every single attribute on every single model is pretty repetitive though. So I rolled my own custom matcher to speed this up. It takes advantage of the fact that I follow the convention of using a valid_attributes method somewhere in my model’s spec, which I use to create a basic object for testing. For example:

describe "Comment" do
  def valid_attributes
    {
      :commentable_type => 'Item',
      :commentable_id => 1,
      :content => "This is a comment!",
      :user_id => 1
    }
  end
  
  before(:each) do
    @comment = Comment.new(valid_attributes)
  end
  
  it "should ..."
end

The new matcher allows me to add a single spec which ensures that the comment validates with exactly these attributes - and no less.

  it "should validate with exactly the specified attributes" do
    @comment.should validate_with_exactly(valid_attributes)
  end

The spec will fail - with an readable error message - if either:

  • The object is invalid with all the specified attribues
  • Any one of the attributes is missing and the object is valid

The spec code is available at http://pastie.org/230565 - pastie it into your spec_helper.rb.

This is still so hot off the press it’s positively steaming. Do you have any comments, bug reports or suggestions?

Bookmark it: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • DZone
  • Reddit
  • StumbleUpon
  • Technorati
  • Facebook

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*