Skip to content

Instantly share code, notes, and snippets.

@fbuys
Created July 1, 2020 15:28
Show Gist options
  • Save fbuys/980b87688b1851dd4fd2e85f4a19ede9 to your computer and use it in GitHub Desktop.
Save fbuys/980b87688b1851dd4fd2e85f4a19ede9 to your computer and use it in GitHub Desktop.
Ruby code for iterating through a list of active record tables, it then saves the active records in yaml format.
TABLES_TO_SKIP = %w[ar_internal_metadata delayed_jobs schema_info schema_migrations].freeze
begin
ActiveRecord::Base.establish_connection
# For all tables uncomment the below
# ActiveRecord::Base.connection.tables.each do |table_name|
# To limit to specific tables uncomment below
['table_name'].each do |table_name|
next if TABLES_TO_SKIP.include?(table_name)
conter = '000'
file_path = "#{Rails.root}/spec/cypress/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
end
@fbuys
Copy link
Author

fbuys commented Jul 1, 2020

Big thanks to: https://yizeng.me/2017/07/16/generate-rails-test-fixtures-yaml-from-database-dump

This function allows me to generate active record fixtures that I can then use for running rspec or cypress tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment