Default attributes from fixtures

When testing a model that has a lot of attributes I keep a default fixture and populate a hash from it, probably not much less effort than creating the hash inline, I just like to keep the code clear of extra fluff.

def load_default_attributes(model_name, options ={})
  fixture = options[:fixture] || :default
  attributes = temp_attributes = model = {}
  instance_eval <<-FIN
    temp_attributes = #{model_name.to_s.pluralize}("#{fixture}")
    model = #{model_name.to_s.capitalize}
  FIN
    drop = [options[:drop], :created_on, :updated_on, :id].flatten
    temp_attributes.attributes.each do |k, v| 
      attributes[k.to_sym] = v unless drop.include? k.to_sym
    end  
    options[:attributes].each {|k, v| attributes[k.to_sym] = v} if options[:attributes]
    if options[:confirmation] 
      options[:confirmation].each do |a| 
        attributes = attributes.merge( {"#{a}_confirmation".to_sym => attributes[a.to_sym]} )
      end 
    end
    return attributes
end

The options;

  • :fixture => "foo" use the fixture "foo" for the default values assuming the fixtures filename is the plural of model_name.
  • :attributes is a hash of attributes that override those retrieved from the fixture.
  • :drop is an array of the attributes you do not want loaded into the hash from the fixture.
  • :confirmation is an array attributes names to create a confirmation for e.g. :confirmation => [:password] will add to the returned hash a key :password_confirmation with the same value as :password.


About this entry