Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 Factories vs Simple Instantiation

Could someone please explain why Factories are more useful than a simple instantiation during test? More clearly, I do not see the difference between:

before(:each) do
  @attr = {
    :name => "Example User",
    :email => "[email protected]",
    :password => "foobar",
    :password_confirmation => "foobar"
  }
end

it "should create a new instance given valid attributes" do
  User.create!(@attr)
end

and this

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

which has the following Factory:

Factory.define :user do |user|
  user.name                  "Michael Hartl"
  user.email                 "[email protected]"
  user.password              "foobar"
  user.password_confirmation "foobar"
end
like image 746
Theo Scholiadis Avatar asked Jan 19 '23 21:01

Theo Scholiadis


1 Answers

The bigger your app gets, the more benefits you gain from factories.

Your solution is great for 2-3 models. But lets say you have an article model where you need valid users to test stuff. Now you have 2 files where you define @attr for users. Now imagine there are even more models that need users, like comments, roles, etc. It gets messy.

It is more convenient to use factories. The benefits are you can define multiple default prototypes. Like an admin user, a normal user, an unregistered user etc.

Furthermore the code is DRY, so if you add a new mandatory field you can add it once to your factory and you are done.

So the answer is: Basically they are the same, but the bigger your app gets the more you need a way to manage all your prototypes.

like image 146
ayckoster Avatar answered Jan 28 '23 16:01

ayckoster