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_require_attributes :name, :phone_number
should_require_unique_attributes :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_require_unique_attributes :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_require_unique_attributes :name
end
end
But Shoulda doesn’t stop at your models. There are some pretty powerful helpers for your controllers as well.