Skip to content

Instantly share code, notes, and snippets.

@semikolon
Created October 25, 2008 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save semikolon/19720 to your computer and use it in GitHub Desktop.
Save semikolon/19720 to your computer and use it in GitHub Desktop.
namespace :spec do
namespace :db do
namespace :fixtures do
desc 'Create YAML spec fixtures from data in an existing database. Defaults to development database. Set RAILS_ENV to override. You can also set tables to dump with rake spec:db:fixtures:dump TABLES=posts,pages'
task :dump => :environment do
sql = "SELECT * FROM %s"
skip_tables = ["schema_info", "schema_migrations"]
ActiveRecord::Base.establish_connection(RAILS_ENV)
tables = ENV['TABLES']
tables ||= (ActiveRecord::Base.connection.tables - skip_tables)
tables.each do |table_name|
i = "000"
fixture = "#{RAILS_ROOT}/spec/fixtures/#{table_name}.yml"
data = ActiveRecord::Base.connection.select_all(sql % table_name)
if File.exist?(fixture)
File.rename(fixture, "#{fixture}.bak")
end
File.open(fixture, 'w') do |file|
file.write data.inject({}) { |hash, record|
hash["#{table_name}_#{i.succ!}"] = record
hash
}.to_yaml
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment