Test data: fixtures vs factories
This course looks at test data in a Rails app that uses RSpec and FactoryBot instead of classic YAML fixtures. It starts with what a Rails fixture is, quoted from Rails' doc comments, and shows that this app has none. It then reads the app's factory files: attributes, sequence, hand-written traits and the enum traits FactoryBot generates automatically. It compares create, build, build_stubbed and attributes_for, explains how associations build related records, and weighs the tradeoff between fixtures and factories. It ends with a plain Ruby object builder challenge.
What you'll learn
- ✓What a classic Rails YAML fixture is and how Rails loads it
- ✓The factory DSL: attribute blocks, sequence counters and call-site overrides
- ✓Hand-written traits and the enum traits FactoryBot defines automatically
- ✓The differences between create, build, build_stubbed and attributes_for
- ✓How factory associations build and save related records in one call
- ✓The tradeoff between fixtures and factories for this app
What a classic Rails fixture is, and why this app has none
active_record/fixtures.rb, installed with this app's Rails 8.1.3.1, opens with a definition: "Fixtures are a way of organizing data that you want to test against; in short, sample data." They're plain YAML, one file per model, in test/fixtures/, Minitest's convention:
Read the full lesson free →Curriculum
7 lessonsWhat a classic Rails fixture is, and why this app has none
Defines a classic Rails YAML fixture from Rails' doc comments and shows this app uses none.
The factory DSL: attributes and sequence, checked against this app's files
Reads the user factory to explain attribute blocks, sequence counters for unique values, and call-site overrides.
Traits: four written by hand, and many nobody wrote
Covers the four hand-written traits and the enum traits FactoryBot generates automatically from model enums.
create, build, build_stubbed, attributes_for: four strategies, checked
Compares create, build, build_stubbed and attributes_for from FactoryBot's source, and how often this suite uses each.
Associations, built and saved on the fly
Shows how association declarations build and save related records in one call, and how to override them.
The tradeoff: why factories won here
Weighs fixture speed for static data against factory flexibility, and explains why this app chose factories.
Putting it together: an object builder with sequences, in plain Ruby
Sums up the defaults, sequences and overrides pattern and sets a plain Ruby object builder challenge.