awesomeprogrammer.com

Sharing ideas

Solving problems

Gathering solutions

Exchanging thoughts

Ruby On Rails

PHP

Postgres

Debian & Ubuntu
jQuery & CSS

Using Factory Girl in Development

There is a time when you need to put some random data in your database. Maybe build up pretty frontend or manually test some features. I was using rake tasks that with a little help from Faker, at least until last few days – I needed to upgrade my tasks, but I mean – I had my test factories that were up-to-date, so I thought – why not use them? And so I did ;). Below is sample rake tasks that build a forum structure:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
require 'factory_girl'

namespace :db do
  desc "Build me a forum!"
  task :populate => :environment do

  # here maybe you want to delete stuff?
  # User.destroy_all or whatever suits your needs

  require Rails.root.join('spec/factories.rb') # Here I keep my factories, it also loads Faker gem
  user_pool = []

  # I'm overriding some FactoryGirl sequences so it doesn't mess with my validation
  10.times { user_pool << FactoryGirl.create(:user, :login => Faker::Internet.user_name,:email => Faker::Internet.email).id }

  # This factory for example will also create forum and sections for the forums that I use
  User.all.each do |user|
    10.times { FactoryGirl.create(:topic, :user => user, :title => Faker::Lorem.sentence) }
  end

  # And this factory just pusts posts for users from pool that I declared before
  Topic.all.each do |topic|
    5.times { FactoryGirl.create(:post, :postable => topic, :user_id => user_pool.sample) }
  end

  end
end

I think it’s much better approach that building new tasks from scratch. Just keep in mind that you may ovrride some attributes (eg. if you are validating uniqness) and you should be just fine.

Comments