public
Description: Makes tests easy on the fingers and the eyes
Home | Edit | New

ActiveRecord Helpers

Shoulda comes armed with a series of ActiveRecord test macros which can really speed up development time, and make TDD a breeze. They’re all documented in the Shoulda RDocs, but here’s a quick example:

class UserTest < Test::Unit::TestCase
  load_all_fixtures

  should_validate_presence_of :name, :phone_number
  should_validate_uniqueness_of :name
  should_not_allow_values_for :phone_number, "abcd", "1234" 
  should_allow_values_for :phone_number, "(123) 456-7890" 

  should_protect_attributes :admin

  should_have_one :profile
  should_have_many :dogs
  should_have_many :messes, :through => :dogs
  should_belong_to :lover
end

This will create the following tests:

test: Person should allow phone_number to be set to "(123) 456-7890". 
test: Person should belong to lover. 
test: Person should have many dogs. 
test: Person should have many messes through dogs. 
test: Person should have one profile. 
test: Person should not allow admin to be changed by update. 
test: Person should not allow phone_number to be set to "1234". 
test: Person should not allow phone_number to be set to "abcd". 
test: Person should require name to be set. 
test: Person should require phone_number to be set. 
test: Person should require unique value for name.

Requirements

One thing to be aware of is that some of the ActiveRecord test macros need to be able to find an initial record (through Class.find(:first)). You can make this work by having a fixture file with a record in it, or by creating a single record in a set up like this:

class UserTest < Test::Unit::TestCase
  def setup
    @user = User.create!(params)
  end

  should_validate_uniqueness_of :name
end

or by using a context like so:

class UserTest < Test::Unit::TestCase
  context "given an existing record" do
    setup do
      @user = User.create!(params)
    end

    should_validate_uniqueness_of :name
  end
end
Last edited by adamhunter, Thu Jul 30 08:08:36 -0700 2009
Home | Edit | New
Versions: