Oct 22 2007
User: cedric
Category: Ruby on Rails
Tags: rails tests fixtures

Fixture generator

I’ve spent time to understand test & fixtures, and sometimes it’s a bit long to check the SQL tables to create fixtures without forgetting one field.

this snippet really helped me but was a bit limited.

I’ve improved it like this:


# 
# fixture_generator.rb
# 
require_gem 'activerecord'

class RailsFixturesGenerator

  def generate(class_name,number)

    # 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" 
    i=0
    while i < number.to_i do
      i+=1
      i==1 ? yaml_content += "first:\n" : yaml_content += "item"+i.to_s+":\n" 
      model_class.columns.each { |column|
        yaml_content += "  " + column.name + ": " 
        case column.type
        when :integer
          yaml_content +=  i.to_s
        when :text
          yaml_content +=  column.name
          yaml_content +=  i.to_s
        when :string
          st="string for item "+i.to_s+" "+column.name
          yaml_content += st[0,column.limit]
        when :datetime
          yaml_content +=  Time.now.strftime("%Y-%m-%d %H:%M:%S")
        else
          st="content_unknown for "+column.type.to_s
          yaml_content+=st[0,column.limit]
        end
        yaml_content += "\n"      
      }  
      yaml_content += "\n" 
    end
    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

It checks length of string fields, fill the datetime fields, etc… and you can choose how many records you want.

To use it:

Create a file called “fixture_generator.rb” in the /lib directory of your application

in a shell:

cd yourapp
ruby script/console
require 'fixture_generator'
a=RailsFixturesGenerator.new
a.generate("Category",3)

You will have a file in /test/fixtures/categories.yml created with 3 complete records ready to be customized for your tests!

comments : 0 Add comment

Back
Log in

Quick links

Localization

Search

weather


  • metric us

gallery

Last comments

  • no new comments

Categories

  • categories

nabaztag

  • message

    left
    right
    voice
    speed
    pitch

hcard