Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factories/Fixtures vs simple Model.create(...)?

What's the purpose of factories/fixtures (I know factories act like fixtures, but a bit clearer) when you can simply use ActiveRecord in your test to create the database entry? i.e. News.create(…)

I just don't see any advantage of using Factory Girl instead of simply create a new let say a new User using ActiveRecord methods..

Thanks

like image 875
allaire Avatar asked Apr 14 '12 16:04

allaire


1 Answers

Factories

Creates/builds an object and then you use it only when called upon in a test.

You define the "happy path" of the object, including associations, in one file (as ryan mentioned) and then just maintain one file for when your schema/model associations change.

Fixtures

Mimics what the database should look like for a single record, it's loaded into the test database and then used.

Fixtures are end state of the model and live in the database, so are loaded once, and can be used in the tests as you see fit.

Multiple files and you lay out your fixture files so that each file and association are taken care of.

NewModel.create(...)

Is created once and used once in one test or in one before(:each) block

If you have 100 of these blocks, that is writing and maintaining 100 different Objects, let alone the Associations like @user.profile.create(....) 100 times.

Advantages of Factories over NewModel.create

One file to maintain, rather than grepping and replacing multiple build or create in your lines of code.

Note It must be said that in my test suite I want it to be quick as possible, so i am dropping FactoryGirl and using Fixtures and NewModel.create moving forward. Just to see if it speeds it up. I'm working on the theory that FG is slowing my suite down, as is let() and before(:each)

like image 92
pjammer Avatar answered Sep 20 '22 15:09

pjammer