I have some data in my development database that I would like to utilize as fixtures in my test environment. What is the best way in Rails 2.x to export a database table to
Very simple gem will create yaml fixtures from existing database...
github.com/vanboom/yaml_dump
Works with Rails 4.
I used this in Rails 6:
# How to run:
# rake fixtures:import_db_table[my_table]
namespace :fixtures do
desc 'Convert development table into Rails test fixtures'
task :import_db_table, [:table_name] => :environment do |_task, args|
begin
table_name = args[:table_name]
raise "Missing table name" if table_name.blank?
conter = '000'
file_path = "#{Rails.root}/spec/fixtures/#{table_name}.yml"
ActiveRecord::Base.establish_connection
File.open(file_path, 'w') do |file|
rows = ActiveRecord::Base.connection.select_all("SELECT * FROM #{table_name}")
data = rows.each_with_object({}) do |record, hash|
suffix = record['id'].blank? ? conter.succ! : record['id']
hash["#{table_name.singularize}_#{suffix}"] = record
end
puts "Writing table '#{table_name}' to '#{file_path}'"
file.write(data.to_yaml)
end
ensure
ActiveRecord::Base.connection.close if ActiveRecord::Base.connection
end
end
end
Extracted from here (which imports all tables).
There is a rake task for this. You can specify RAILS_ENV if needed; the default is the development environment:
rake db:fixtures:dump
# Create YAML test fixtures from data in an existing database.
Iron Fixture Extractor was built for exactly this purpose. It's particularly good for situations where you want to use different fixture sets for different testing scenarios (rather than having all fixtures for all tests). It provides functionality for extracting, loading, rebuilding fixtures, truncating tables, or snagging particular hashes from your fixture yaml files.
This plugin will add the functionality you want. It was extracted from ActiveRecord so no longer comes by default.
script/plugin install http://github.com/topfunky/ar_fixtures
Then run:
rake db:fixtures:dump MODEL=ModelName