Use of Fixtures Data in Tests

Learn how to use fixtures data in your tests.

Using fixtures data

Now that we know how to get fixture data into the database, we need to find ways of using it in our tests.

Clearly, one way would be to use the finder methods in the model to read the data. However, Rails makes it even easier than that. For each fixture it loads into a test, Rails defines a method with the same name as the fixture. We can use this method to access preloaded model objects containing the fixture data. Simply pass it the name of the row as defined in the YAML fixture file, and it’ll return a model object containing that row’s data.

In the case of our product data, calling products(:ruby) returns a Product model containing the data we defined in the fixture. Let’s use that to test the validation of unique product titles:

Get hands-on with 1200+ tech skills courses.