我已经为测试 Rails 项目构建了一些精心制作的 FactoryGirl 工厂定义,为此它们运行良好。
我现在想在脚本(Ruby、Rake 等等)中使用相同的定义,用大量有效的、正确关联的记录来填充 Rails 开发数据库。
我确定这是一项常见任务,但找不到有用的引用。
什么是最佳实践?如何进行?
假设工厂在 spec/factories.rb
.接下来是什么?谢谢。
更新
还在挣扎。尝试将此作为 rake
任务。
require 'factory_girl'
require 'spec/factories'
namespace :db do
desc "Fill database with trial data"
task :populate => :environment do
Rake::Task['db:reset'].invoke
50.times do |n|
# Make a consistent set of related records.
team = FactoryGirl.create(:team, :completed)
team.members << FactoryGirl.create(:member)
FactoryGirl.create(:design, :team => team)
end
end
end
唉,这找不到我的
factories.rb
:rake aborted!
cannot load such file -- spec/factories
在其他任何地方,项目根相对需要路径都可以正常工作。什么是 secret 握手?
最佳答案
正如我在评论中提到的,这通常是种子数据的工作。如果您只想将此数据植入开发数据库,您可以修改 seed
通过做这样的事情来 rake 任务:
namespace :db do
task :seed => :environment do
env_seed_file = File.join(Rails.root, 'db', 'seeds', "#{Rails.env}.rb")
load(env_seed_file) if File.exist?(env_seed_file)
end
end
这将使您能够为每个环境创建一个文件(即 db/seeds/development.rb)。你也可以使用像 seedbank 这样的 gem它为您提供了特定于环境的种子文件以及对 Rails 中已有内容的一些其他补充。
关于ruby-on-rails - 如何使用FactoryGirl工厂搭建开发数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15777731/