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
Have you ever wanted to render a partial to a string from inside a model?
This solution was inspired by this snippet showing how to use view helpers in a controller. It’s clean and simple, no need to mess with ERB or metaprogramming!
class Model
class Helper < ActionView::Base
include Singleton
end
def help
Helper.instance
end
...
def summarize
## Note that we have to use the FULL path here!
help.render( :partial => "#{RAILS_ROOT}/app/views/notifications/text_order_summary", :object => self )
end
alias_method :to_s, :summarize
end

