Last active
April 30, 2020 07:37
-
-
Save DmytroVasin/0e35d7b61673cdb066f136201bc641bb to your computer and use it in GitHub Desktop.
Generate Rails test fixtures yaml from database dump
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace :db do | |
desc 'Convert development DB to Rails test fixtures' | |
task to_fixtures: :environment do | |
TABLES_TO_SKIP = %w[ar_internal_metadata delayed_jobs schema_info schema_migrations].freeze | |
begin | |
ActiveRecord::Base.establish_connection | |
ActiveRecord::Base.connection.tables.each do |table_name| | |
next if TABLES_TO_SKIP.include?(table_name) | |
conter = '000' | |
file_path = "#{Rails.root}/test/fixtures/#{table_name}.yml" | |
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 | |
end | |
ensure | |
ActiveRecord::Base.connection.close if ActiveRecord::Base.connection | |
end | |
end | |
end | |
################### RESULT #################### | |
rake db:to_fixtures | |
--- | |
country_1: | |
id: 1 | |
name: New Zealand | |
created_at: '2017-02-20 08:56:18.481455' | |
updated_at: '2017-02-20 08:56:18.481455' | |
country_2: | |
id: 2 | |
name: United States | |
created_at: '2017-02-20 09:51:23.430189' | |
updated_at: '2017-02-20 09:51:23.430189' | |
country_3: | |
id: 3 | |
name: Deutschland | |
created_at: '2017-02-20 09:53:23.819761' | |
updated_at: '2017-02-20 09:53:23.819761' | |
Read more: https://yizeng.me/2017/07/16/generate-rails-test-fixtures-yaml-from-database-dump/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment