DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Generate Rails Fixture Skeleton Using ActiveRecord

08.10.2006
| 8407 views |
  • submit to reddit
        In Rails 1.1.5, the basic generator generates the following code for the fixture used in database unit tests:
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
first:
  id: 1
another:
  id: 2

As ActiveRecord provides database reflexion features, we can generate a fixture file with all the columns' name prepopulated for number and text types, such as:
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
first:
  id: 1
  short_title: short_title_first
  title: title_first

This will be done by the following class:
require_gem 'activerecord'

class RailsFixturesGenerator

  def generate(class_name)
    
    # Get the "Class" object from the class name        
    model_class = Object.const_get(class_name)
    
    yaml_content =  "# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html\n"
    yaml_content += "first:\n"
    
    # get if first!   
    model_class.columns.each { |column|
      
      yaml_content += "  " + column.name + ": "
      
      if column.number?
        yaml_content +=  "1"
      end
      if column.text?
        # @todo /!\ max length
        yaml_content +=  column.name + "_first"
      end
      
      yaml_content += "\n"      
    }  
    
    write_fixture_file(model_class, yaml_content)
    
    yaml_content            
  end  
  
  # Write the <fixture> yaml file  in the test/fixtures folder
  def write_fixture_file(model_class, yaml_content)
    
    path = ENV['DEST'] || "#{RAILS_ROOT}/test/fixtures"
    db   = ENV['DB']   || 'test'
    
    File.open("#{path}/#{model_class.table_name}.yml", 'wb') do |file|    
      file.write yaml_content 
      file.close    
    end
  end
end

Of course, I have an unit test that I wrote before the code ;-)
This was my first "complex" method I wrote in Ruby so please bear with me. Any feedback is welcome. I want to write a Rails plugin in order to share the generators I will write.     

Comments

Nic Williams replied on Thu, 2006/04/20 - 7:32am

Schema based fixtures are a wonderful idea. I've been thinking of adding model generation to Dr Nic's Magic Models (http://drnicwilliams.com/2006/08/07/ann-dr-nics-magic-models/), I think adding this extended fixture generation at the same time would be a great tool. Good work. Nic