Over a million developers have joined DZone.

Generate Rails Fixture Skeleton Using ActiveRecord

·
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  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. 
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}