Skip to content

Instantly share code, notes, and snippets.

@royratcliffe
Created August 1, 2011 14:12
Show Gist options
  • Save royratcliffe/1118192 to your computer and use it in GitHub Desktop.
Save royratcliffe/1118192 to your computer and use it in GitHub Desktop.
Rake task for writing YAML-formatted test fixtures using current database
namespace :db do
namespace :fixtures do
desc "Write YAML-formatted test fixtures using current database"
task :write_yml, [:limit] => [:environment] do |t, args|
args.with_defaults(:limit => nil)
write_active_record_tables('.yml', args.limit) do |output_stream, records|
# Important not to write the records as an array; write them as a hash.
# Use the "id" as the unique hash key. This formats the fixture in
# standard unordered layout.
hash = {}
records.each { |record| hash["#{record.class.table_name.singularize}_#{record.id}"] = record.attributes }
output_stream.write(hash.to_yaml)
end
end
# Answers an array of table-name strings, one string element for every
# database table with a matching model under app/models. Table names are
# plural, as standard. Assumes that you have already established the
# active-record connection.
def active_record_tables
ActiveRecord::Base.connection.tables.select do |table_name|
File.exists?(File.join(Rails.root, 'app', 'models', table_name.singularize + '.rb'))
end
end
# Iterates through every table, opening an appropriate fixture file at
# spec/fixtures. Then invokes the given block, passing the output stream and
# array of active records. Your block writes the records using a format
# matching the given extension, i.e. YAML or CSV.
def write_active_record_tables(extension, limit)
active_record_tables.each do |table_name|
klass = table_name.classify.constantize
records = klass.limit(limit).all
puts "Writing #{records.length} #{klass} fixtures"
yield File.open(File.join(Rails.root, 'spec', 'fixtures', table_name + extension), 'w'), records
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment