I have already built some elaborate FactoryGirl factory definitions for testing a Rails project, and for this purpose they are working well.
I'd now like to use the same definitions with a script (Ruby, Rake, whatever...) to populate the Rails development database with a large collection of valid, correctly associated records.
I'm sure this is a common task but cannot find a useful reference.
What is best practice? How to proceed?
Say the factories are in spec/factories.rb
. What next? Thanks.
Update
Still struggling. Tried this as a rake
task.
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
Alas, this can't find my factories.rb
:
rake aborted!
cannot load such file -- spec/factories
Everywhere else a project root-relative require path works fine. What is the secret handshake?
As I mentioned in my comment, this is typically the work of seed data. If you want this data to only be seeded into your development database, you could modify the seed
Rake task by doing something like this:
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
which would give you the ability to create a file for each environment (i.e. db/seeds/development.rb). You could also use a gem like seedbank which gives you environment specific seed files and a few other additions to what's already in Rails.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With