Regenerate fixture test files in Rails

99封情书 提交于 2020-01-03 17:48:11

问题


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


回答1:


@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



来源:https://stackoverflow.com/questions/9915726/regenerate-fixture-test-files-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!