简体   繁体   中英

Regenerate fixture test files in Rails

How do I regenerate all the YML fixture files? I accidentally deleted them.

@brian,

I'm using the following script to generate the fixtures from a given sql

This is under my lib/task directory as a rake task

namespace :fixture_generator do
  desc "generate fixtures for a given sql query from the current development database"

  task :fixture_generator, [:sql, :file_name] => :environment do |t, args|
    args.with_defaults(:sql => nil, :file_name => nil)
    i = "000"
    p "creating fixture - #{args.file_name}"
    File.open("#{Rails.root}/test/fixtures/#{args.file_name}.yml", 'a+') do |file|
      data = ActiveRecord::Base.connection.select_all(args.sql)
      file.write data.inject({}) { |hash, record|
        number = i.succ!
        hash["#{args.file_name}_#{number}"] = record
        hash
      }.to_yaml
    end

  end
end

Usage, Say I want to generate fixture for users table

rake fixture_generator:fixture_generator["select * from users","users"]

And also, If you run another query with the same fixture file name, it will append to the existing one

HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM