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

Peter has posted 12 posts at DZone. View Full User Profile

Create YAML Test Fixtures From Database In Rails

09.03.2006
| 33277 views |
  • submit to reddit
        As found at <a href="http://media.pragprog.com/titles/fr_rr/code/CreateFixturesFromLiveData/lib/tasks/extract_fixtures.rake">http://media.pragprog.com/titles/fr_rr/code/CreateFixturesFromLiveData/lib/tasks/extract_fixtures.rake</a>

desc 'Create YAML test fixtures from data in an existing database.  
Defaults to development database.  Set RAILS_ENV to override.'

task :extract_fixtures => :environment do
  sql  = "SELECT * FROM %s"
  skip_tables = ["schema_info"]
  ActiveRecord::Base.establish_connection
  (ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
    i = "000"
    File.open("#{RAILS_ROOT}/test/fixtures/#{table_name}.yml", 'w') do |file|
      data = ActiveRecord::Base.connection.select_all(sql % table_name)
      file.write data.inject({}) { |hash, record|
        hash["#{table_name}_#{i.succ!}"] = record
        hash
      }.to_yaml
    end
  end
end
    

Comments

Snippets Manager replied on Tue, 2009/02/10 - 5:17am

You can use 'ya2yaml' to generate Unicode fixture files in UFT8 format. Just install the ya2yaml gem "gem install ya2yaml", then include ya2yaml in your project " require 'ya2yaml' ", then use .ya2yaml instead of .to_yaml

Snippets Manager replied on Mon, 2012/05/07 - 2:27pm

# Updated to add to db namespace and to specify particular tables in FIXTURES, e.g FIXTURES=table1,table2 namespace :db do desc 'Create YAML test fixtures from data in an existing database. Defaults to development database. Set RAILS_ENV to override.' task :extract_fixtures => :environment do sql = "SELECT * FROM %s" skip_tables = ["schema_info", "sessions"] ActiveRecord::Base.establish_connection tables = ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : ActiveRecord::Base.connection.tables - skip_tables tables.each do |table_name| i = "000" File.open("#{RAILS_ROOT}/db/#{table_name}.yml", 'w') do |file| data = ActiveRecord::Base.connection.select_all(sql % table_name) file.write data.inject({}) { |hash, record| hash["#{table_name}_#{i.succ!}"] = record hash }.to_yaml end end end end