How to generate fixtures based on my development database?
The question is old, but as it still seems relevant: yes, there is an easy way to create fixtures from your development database:
class ActiveRecord::Base
def dump_fixture
fixture_file = "#{Rails.root}/test/fixtures/#{self.class.table_name}.yml"
File.open(fixture_file, "a+") do |f|
f.puts({ "#{self.class.table_name.singularize}_#{id}" => attributes }.
to_yaml.sub!(/---\s?/, "\n"))
end
end
end
Place this in a file in config/initializers
- now you can dump any ActiveRecord object in your Rails console and it will automatically be appended at the end of it's respective fixture file:
User.first.dump_fixture
appends fixture data to test/fixtures/users.yml
.
Building on @nikolasgd's answer I wrote a Rake Task, which may be useful for some:
# Use like "rake custom:create_test_fixtures[model]"
namespace :custom do
desc 'Re-Creates Fixtures for Testing for a Model'
task :create_test_fixtures, [:model] => [:environment] do |t, args|
class ActiveRecord::Base
def dump_fixture
fixture_file = "#{Rails.root}/test/fixtures/#{self.class.table_name}.yml"
File.open(fixture_file, "a+") do |f|
f.puts({"#{self.class.table_name.singularize}_#{id}" => attributes}.
to_yaml.sub!(/---\s?/, "\n"))
end
end
end
begin
model = args[:model].constantize
model.all.map(&:dump_fixture)
puts "OK: Created Fixture for Model \"#{args[:model]}\"."
rescue NameError
puts "ERROR: Model \"#{args[:model]}\" not found."
end
end
end
In case you're creating a script to run under rails runner
you can use the following approach:
File.open("#{Rails.root}/spec/fixtures/documents.yml", 'w') do |file|
file.write Document.all.to_a.map(&:attributes).to_yaml
end
you can create as much blocks as you want, or if you want to go to the full database you can try:
models = defined?(AppicationRecord) ? ApplicationRecord.decendants : ActiveRecord::Base.descendants
models.each do |model|
model_name = model.name.pluralize.underscore
File.open("#{Rails.root}/spec/fixtures/#{model_name}.yml", 'w') do |file|
file.write model.all.to_a.map(&:attributes).to_yaml
end
end
if you do not want the timestamps you can change the code to:
model.all.to_a.map { |m| m.attributes.except('created_at', 'updated_at')}.to_yaml