FactoryGirl in Development Environment

Blog ยป FactoryGirl in Development Environment

Posted on 03 Dec 2010 01:15

You can use FactoryGirl to populate the databse during development. You need Factories for test. But I don't see any reason that you cannot use them in development environment also.

Lets say you have those factories

require 'factory_girl'
unless Factory.factories[:user]
Factory.define :admin, :class=> User do |u|
  u.sequence(:name ){|n| "admin#{n}"}
  u.sequence(:email_address ){|n| "admin#{n}@test.com"}
  u.password 'pass'
  u.administrator true
Factory.define :user do |u|
  u.sequence(:name ){|n| "user#{n}"}
  u.sequence(:email_address ){|n| "user#{n}@test.com"}
  u.password 'pass'
  u.administrator false
require 'factory_girl'
unless Factory.factories[:organization]
Factory.define :organization do |m|
  m.sequence(:name) {|n| "Test Organization #{n}"}

Then you can define such a rake task to populate your database

namespace :app do
desc 'Fill database with test data'
task :populate => [:environment, "db:reset"] do
  require 'factory_girl'
  Dir['test/factories/*.rb'].each { |f| require f[0..-4] }
  p "Manifacturing Objects..."
  (1..2).each  { Factory(:organization) }

Now go and type

rake app:populate

If you like this page, please spread the word: diggdel.icio.usFacebook

You can contact me if you have questions or corrections.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License