如何重新生成所有YML夹具文件?我不小心删除了它们。
@brian,
我使用以下脚本从给定的sql生成fixture
这是在我的lib/task目录下,作为一个rake任务
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
用法,比如我想为用户生成fixture表
rake fixture_generator:fixture_generator["select * from users","users"]
此外,如果您使用相同的fixture文件名运行另一个查询,它将附加到现有的
HTH
当我在我们的应用程序中使用Nested Set时(这里说MyTree模型),在使用之前(当然在测试期间)需要计算lft/rgt列。为了在MyTree的fixture中为所有记录设置collect lft/rgt,有一些方法:
- a) 手动写下所有mytrees.yml条目的计算lft/rgt值
- b) 执行MyTree.rebuild!在CCD_ 1块中进行每个必要的测试
- c) 生成具有lft/rgt值的计算夹具文件
a) 以上对于人类来说是相当乏味的任务。b) 在每个CCD_ 2的测试期间消耗CPU资源。我认为c)是最好的方法,所以我在这里发布我的代码。
@sameera207的代码不能应用于我们的情况,因为我使用Label引用作为fixture条目,所以我编写了下面的"rake任务",它从test/fixtures.src/my_trees.yml
生成test/fixtures/my_trees.yml
:
例如,数据模型为:
class MyTree < ApplicationRecord
acts_as_nested_set
...
end
生成任务为:
namespace :my_app do
desc 'rebuild from test/fixtures.src/my_trees.yml to test/fixtures/my_trees.yml'
task rebuild_my_trees_fixture: :environment do
require 'active_record/fixtures'
if !Rails.env.test?
puts('not test env')
next
end
id_to_entry = {} # ActiveRecord::FixtureSet#idnetity -> entry name
for key, val in YAML.load(ERB.new(File.read('test/fixtures.src/my_trees.yml'), 0, '-').result) do
id_to_entry[ActiveRecord::FixtureSet.identify(key)] = key
end
MyTree.transaction do
MyTree.delete_all
# load source to DB
::ActiveRecord::FixtureSet.create_fixtures('test/fixtures.src', 'my_trees')
MyTree.rebuild!(false)
File.open(Rails.root + 'test/fixtures/my_trees.yml', 'w') do |f|
# write header
f.write <<~EOS
# ===================================================================
# Do not modify this file manually!!
# This file is automatically generated.
# ===================================================================
EOS
hash = {}
for rec in MyTree.all do
key = id_to_entry[rec.id]
if key.nil?
STDERR.printf("ERROR: entry not found for id(%d)n", rec.id)
else
hash[id_to_entry[rec.id]] = rec.attributes.except('id')
end
end
f.write(hash.to_yaml)
end
# cache should be cleaned here. Otherwise this working my_trees table
# remains at the 'rake test' later.
::ActiveRecord::FixtureSet.reset_cache
raise ActiveRecord::Rollback
end
end
end
# invoke above task before 'rake test'
task :'test' => 'my_app:rebuild_my_trees_fixture'
关键点是上面代码中的MyTree.rebuild!
,它计算所有条目的所有lft/rgt。上述代码的所有其他片段都只是准备和生成。
TODO
我没有时间编写fixtures.src/my_trees.yml
和test/fixtures/my_trees.yml
之间的文件依赖触发器调用的任务。