Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Railstutorial: db:populate vs. factory girl

In the railstutorial, why does the author choose to use this (Listing 10.25): http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-users

namespace :db do
  desc "Fill database with sample data"
  task :populate => :environment do
    Rake::Task['db:reset'].invoke
    User.create!(:name => "Example User",
                 :email => "[email protected]",
                 :password => "foobar",
                 :password_confirmation => "foobar")
    99.times do |n|
      name  = Faker::Name.name
      email = "example-#{n+1}@railstutorial.org"
      password  = "password"
      User.create!(:name => name,
                   :email => email,
                   :password => password,
                   :password_confirmation => password)
    end
  end
end

to populate the database with fake users, and also (Listing 7.16) http://ruby.railstutorial.org/chapters/modeling-and-viewing-users-two

Factory.define :user do |user|
  user.name                  "Michael Hartl"
  user.email                 "[email protected]"
  user.password              "foobar"
  user.password_confirmation "foobar"
end

It appears that both ways creates users in the database right (does factory girl create users in the database)? What is the reason for the two different ways of creating test users, and how are they different? When is one method more suitable than the other?

like image 729
Justin Avatar asked Jun 12 '11 01:06

Justin


1 Answers

Faker and Factory Girl are being used in those examples for two different purposes.

A rake task is created using Faker to easily let you populate a database, typically the development database. This lets you browse around your app with lots of populated, fake data.

The factory definition makes tests convenient to write. For example, in your RSpec tests you can write:

before(:each) do
 @user = Factory(:user)
end

Then @user is available in the tests that follow. It will write these changes to the test database, but remember that these are cleared each time you run tests.

like image 59
nmunson Avatar answered Nov 15 '22 11:11

nmunson