Dumping your data into fixtures
The following code will dump your table data into fixtures that you can use for your tests. This is useful if the database needs to contain a known set of data before your tests are run.
This is modified heavily from this DZone snippet: http://snippets.dzone.com/posts/show/4468
namespace :db do
namespace :fixtures do
desc 'Dumps all models into fixtures.'
task :dump => :environment do
(ActiveRecord::Base.connection.tables - ['schema_migrations']).each do |table|
puts "Dumping #{table}"
rows = ActiveRecord::Base.connection.select_all("SELECT * FROM #{ActiveRecord::Base.connection.quote_table_name(table)} ORDER BY id ASC")
out = {}
rows.each_with_index { |mi, i| out["#{table.singularize}_#{i + 1}"] = mi }
model_file = RAILS_ROOT + "/spec/fixtures/#{table}.yml"
File.exists?(model_file) ? File.delete(model_file) : nil
File.open(model_file, 'w') {|f| f << YAML.dump(out).gsub("<%", "<%%") }
end
end
end
end01:20 PM on Monday, 22/06/2009
