What's the difference between a fixture and a factory in my unit tests?
Asked Answered
S

3

12

A little confused here, what is the difference between a factory and a fixture?

So I'm using factory_girl, when I create an object using the factory, should it be persisted to the db? Or is that what a fixture is, data persisted to the db via the models etc.

Or are these totally unrelated :)

Sapphirine answered 16/10, 2011 at 18:3 Comment(0)
L
22

The really short answer is that there is no difference conceptually between a Rails fixture and a Factory Girl factory. This is just different syntax to accomplish the same thing.

However, this gets confusing because the terminology of general testing/coding concepts has been co-opted by individual projects in the Rails/Ruby world. In general:

Basically in Rails, both Fixtures and Factories (as defined by Factory Girl), are just ways of creating objects. You are supposed to use them to create your Test Fixture, or the setup state of your test. The confusing part is that you can use multiple Rails "Fixtures" to create the Fixture (baseline) of an individual test.

Factory Girl itself is an implementation of the Object Mother pattern, that describes a way of creating test fixture setup using personas.

Leprosy answered 17/10, 2011 at 2:23 Comment(2)
Unfortunately, on Fowler's page, he links a paper from xpuniverse.com, which is now gone.Perpetuate
The paper can be found here: citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.18.4710 @PerpetuateLeprosy
D
5

Well they are used to achieve the same goal, to populate the DB with data for your test.

Fixtures are way faster than factories because they don't use validation or any of the model's logic but are very hard to maintain and the lack of validation can break your tests.

With factories you have meaningful (and valid) content in the DB at the cost of speed.

There are other solutions though like fixture_builder that let you define the fixtures using factories ;) the factories are run just once and then converted to fixtures. https://github.com/rdy/fixture_builder

Diction answered 16/10, 2011 at 18:53 Comment(0)
R
1

A Factory, using factory_girl for instance, is only a mean to build objects with predefined values. It doesn't require your to insert them into any kind of persisted store. It is just convenient to build complex objects. factory_girl has obviously many more features, but that is its primary goal as I see it.

NOTE : I'm answering only half of the question here because I'm not very familiar with the fixture... just throwing my 2 cents here. Hope this helps.

Real answered 16/10, 2011 at 19:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.