Sunday, December 11, 2011

Generate .yml fixtures from database tables

Hello Guys,
          Wondering about how to create fixtures from tables? Here is the simple task which generate .yml from database tables.

namespace :db do
  desc 'Generate .yml test fixtures from an existing database'
  task :generate_fixtures => :environment do
    sql = "Select * From %s"
    skip_tables = ["schema_migrations"]
    ActiveRecord::Base.establish_connection
    tables = ActiveRecord::Base.connection.tables - skip_tables
    tables.each do |table_name|
      count = "0000"
      File.open("#{RAILS_ROOT}/db/fixtures/#{table_name}.yml", 'w') do |file|
        table_content = ActiveRecord::Base.connection.select_all(sql % table_name)
        file.write
table_content.inject({}) { |hash, record|
          hash["#{table_name}_#{
count.succ!}"] = record
          hash
        }.to_yaml
      end
    end
  end
end

When you invoke above task using rake db:generate_fixtures --trace. It generates all the fixtures of your database tables under db/fixtures folder of your rails application.

create_fixtures(fixtures_directory, table_names, class_names = {}) is the inbuilt method available to create fixtures for testing.

No comments:

Post a Comment