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?
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.
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