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 :)
A test fixture is a fixed state of a set of objects used as a baseline for running tests. The purpose of a test fixture is to ensure that there is a well known and fixed environment in which tests are run so that results are repeatable.
Fixture Factory is a tool to help developers quickly build and organize fake objects for unit tests. The key idea is to create specification limits of the data (templates) instead of hardcoded data.
It has a benefit of clarity and low overhead. Like I said above, I've definitely used factories more than fixtures. My main reason is that when I use factories, the place where I specify the test data and the place where I use the test data are close to each other. With fixtures, on the other hand, the setup is hidden.
RSpec provides an easy API to write assertions for our tests, while Factory Bot allows us to create stubbed in data for our tests.
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.
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
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