Thoughtbot’s Shoulda is a very nice piece of work. Their ActiveRecord macros are also a god-send:


1 should_protect_attributes :family_id, :debit_account_id, :credit_account_id, :created_at, :updated_at

This code will assert that ActiveRecord attributes are somehow protected (either though attr_accessible or attr_protected). But what about the reverse? There isn’t a macro to do that. I happened to need it, so I implemented it on my own fork of Shoulda.

This allows us to specify:


1 should_protect_attributes :family_id, :debit_account_id, :credit_account_id, :created_at, :updated_at
2 should_allow_attributes :family, :debit_account, :credit_account, :amount, :posted_on, :description

NOTE: Example taken from my family budget application.

I was working on my family budget application and wanted to validate existing fixtures. I wrote the following:

test/shoulda_macros/validation_macros.rb

1 module ValidationMacros
2 def self.included(base)
3 base.send :extend, ClassMethods
4 end
5
6 module ClassMethods
7 def should_have_valid_fixtures(klass=self)
8 should "have all valid fixtures" do
9 klass.name.sub("Test", "").constantize.all.each do |object|
10 assert object.valid?, "Fixture #{object.inspect} is invalid"
11 end
12 end
13 end
14 end
15 end
16
17 Test::Unit::TestCase.send :include, ValidationMacros
18
19 # Usage Example
20 class AccountTest < Test::Unit::TestCase
21 should_have_valid_fixtures
22 end
23
24 class StrangeNameTest < Test::Unit::TestCase
25 # Pass the ActiveRecord (or anything that respond_to?(:valid?)
26 # and respond_to?(:all)) class to validate against.
27 should_have_valid_fixtures Account
28 end

This might be interesting if you use fixtures.

Search

Your Host

A picture of me

I am François Beausoleil, a Ruby on Rails and Scala developer. During the day, I work on Seevibes, a platform to measure social interactions related to TV shows. At night, I am interested many things. Read my biography.

Top Tags

Books I read and recommend

Links

Projects I work on

Projects I worked on