I like to use factory test helpers to generate attributes which I then pass to ActiveRecord. The default output is expected to be valid (hence the usage with create-bang below). If you want to override any of the defaults, you can simply use Hash#merge.
Here’s an example, using shoulda. It should be pretty clear how it can be applied to vanilla Test::Unit (or the testing framework du jour ;).
## I put this in test_helper.rb so I can use it across all tests. ## You could put it in the actual derived test class as well. def valid_user_attrs( unique = DateTime.now ) { :email => "{unique.hash.abs}@example.com", :first_name => "dummy", :last_name => "user_#{unique}", :profile_attributes => valid_profile_attrs } end def valid_profile_attrs ... end## Here’s the actual test caseclass UserTest < Test::Rails::TestCase context "Two Users" do setup do @user = User.create!( valid_user_attrs ) @user2 = User.create!( valid_user_attrs.merge( :email => "dummy123@dummy.com" ) ) end should "not be friends" do assert !@user.friends.include?( @user2 ) assert !@user2.friends.include?( @user ) end end end


December 24th, 2007 at 06:23 PM
I usually do the same thing, except naming them hashformodel. Then, I typically create creation helpers as well.
def create_user(opts={}) User.create(hashforuser(opts)) end