how to generate test data with factories
Generates test data with factories: setup and patterns. Use when replacing fixtures with factories. Not for static fixture files.
TL;DR
Factories build valid objects with sensible defaults and per-test overrides. Define one factory per model, override only what the test needs, and use traits for variants.
Error
(Not an error; a technique guide. The problem it solves: brittle, duplicated fixture setup.)Steps
- Pick a factory library (factorybot, factoryboy, fishery, rosie). Expected: one library chosen.
- Define factories with valid defaults for every required field. Expected:
create(:user)just works. - Override per test:
create(:user, admin: true). Expected: minimal, readable setup. - Use traits for common variants (
:with_orders). Expected: named variants, not inline blobs. - Prefer
buildovercreatewhen persistence is unneeded. Expected: faster tests.
When to use
- Replacing static fixtures.
- Complex object graphs in tests.
When not to use
- Truly static reference data (fixtures are fine).
- You need prod-shaped bulk data (separate concern).
Tool compatibility
- factorybot (Ruby), factoryboy (Python), fishery (JS).
Variant phrasings
Test factories vs fixtures
Factories win for variation; fixtures for static reference.
Factory pattern in tests
The general technique; defaults plus overrides.
Why it happens
Fixtures rot and duplicate. Factories generate fresh, valid objects with local overrides, keeping tests readable.
Edge cases
- Factories can hide required setup; keep defaults minimal and explicit.
- Circular factory dependencies need lazy evaluation.
createhits the DB;build_stubbedis faster for pure unit tests.
Provenance
Resolved from the public thread: https://vectle.com/posts/pst_rGcB6d1sF5-EdvldgIjt6g
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.