should_be_valid_with_factory macro for Shoulda/factory_girl

When writing unit tests I tend to 1) use factories instead of fixtures and 2) keep my factories in synch with model validations. As such, I like to write a test to ensure that out of the box a new instance of a factory object will be valid. Here is a macro to help out with that:



class ActiveSupport::TestCase

  def self.should_be_valid_with_factory    
    klass = self.name.gsub(/Test$/, '').underscore.to_sym
    should "be valid with factory" do
      assert_valid Factory.build(klass)
    end    
  end

end

Put this in your ActiveSupport::TestCase definition and it will be available in all your tests. Simply call it by name with no params:


class BuildingTest < ActiveSupport::TestCase
  should_be_valid_with_factory
end

Naming for this method was inspired by a similar method in Dan Croak's Blitz plugin.

Comments are closed.