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
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).