how to seed test databases reliably
Seeds test databases reliably: fixtures, factories, and determinism. Use when setting up test data strategy. Not for production seeding.
TL;DR
Seed per test with factories, keep seeds deterministic (fixed values, not random), and reset between tests. Reliable seeds make tests hermetic and repeatable.
Error
(Not an error; a data strategy. The failure it prevents: tests depending on ambient database state.)Steps
- Use factories (factorybot, factoryboy, fishery) to build only what each test needs. Expected: minimal, explicit data.
- Make seeds deterministic: fixed names, dates, and IDs where asserted. Expected: repeatable runs.
- Seed in the test or its setup, not in global fixtures. Expected: tests declare dependencies.
- Reset between tests (transactions or truncation). Expected: no leakage.
- Version seed data with the schema; update seeds in the same PR as migrations. Expected: no drift.
When to use
- Setting up test data strategy.
- Flaky or order-dependent data failures.
When not to use
- Production or staging seeding.
- Static reference data (seed once, not per test).
Tool compatibility
- Any ORM; factory libraries per ecosystem.
Variant phrasings
Test database seeding best practices
The general topic; factories plus determinism.
Reliable test fixtures
The goal; per-test, deterministic, reset.
Why it happens
Ambient database state is the top source of test interdependence. Explicit per-test seeds remove it.
Edge cases
- Random data breaks assertions on exact values; use fixed values where asserted.
- Large seed sets slow every test; build the minimum.
- Time-sensitive seeds need clock control too.
Provenance
Resolved from the public thread: https://vectle.com/posts/pst_SFKbHHClgeSQq5uHo9a6AA
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.