将数据库内容导出为fixture

fixture在ruby程序测试过程中能够方便地组织test case.
在某些情况下,又可能需要从数据库导出内容为fixture.
经过一番搜索,找到如下方法:

desc "export the database models to YML fixtures"
task(:models_to_fixtures => :environment) do
ActiveRecord::Base.establish_connection(
:adapter => 'mysql', # mysql, sqlite3
:encoding => 'utf8',
:database => 'database',
:username => 'username',
:password => 'password'
)
ActiveRecord::Base.connection

if ENV['MODELS'].nil? || ENV['MODELS'].blank?
raise "Please enter valid models names separated by coma. Ex: MODELS=User,Account"
end

models = ENV[‘MODELS’].split(‘,’).collect { |arg| arg.camelize.constantize }

models.each do |model|
output = {}
collection = model.find(:all)
collection.each do |object|
output.store(object.to_param, object.attributes)
end
# this file path must exist
file_path = "/tmp/#{model.table_name}.yml" # /tmp/
File.open(file_path, "w+") { |file| file.write(output.to_yaml) }
end
end

保存为Rakefile
然后rake models_to_fixtures即可。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注