Sub topic 8
Migrations, seed data, and keeping tests isolated
This chapter assumes you can already start a PostgreSQL service container and reach it from a job, as covered in the earlier chapters. Here the focus is on what happens inside the database once it is running.
Why the data lifecycle matters
A service container starts empty. Every workflow run gets a fresh container, so nothing carries over from a previous run. That is a benefit: a run never fails because of leftover rows from yesterday. But it also means your job must build the schema itself before any test can run.
Within a single run the opposite problem appears. All tests in the job share one database. If one test leaves rows behind, a later test may see them and fail, or pass for the wrong reason.
You need to handle three things:
- Create the schema with migrations.
- Load any reference data the tests expect.
- Isolate tests from each other.
Run migrations as a step
Run migrations in a step after checkout and dependency installation, and before the tests. The health check from the earlier chapter guarantees the database accepts connections by the time your first step runs, so the migration step can connect immediately.
name: integration-tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: postgres
POSTGRES_DB: app_test
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U postgres"
--health-interval 10s
--health-timeout 5s
--health-retries 5
env:
DATABASE_URL: postgres://postgres:postgres@localhost:5432/app_test
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- name: Apply migrations
run: npm run db:migrate
- name: Load reference data
run: npm run db:seed
- run: npm run test:integrationThe DATABASE_URL is set once at the job level, so the migration, seed, and test steps all use the same database.
Use the same migration tool and the same migration files that production uses. Running them in CI also tests the migrations themselves. A broken migration fails the job before any test runs.
Seed only what tests cannot create themselves
Seed data is data that must exist before tests start, such as country codes, roles, or feature flags. Keep this set small and stable. Tests should create their own records for anything else, because a test that depends on a large shared fixture is hard to read and breaks when the fixture changes.
Make the seed script safe to run twice. Use an upsert, for example INSERT ... ON CONFLICT DO NOTHING, so a retried step does not fail on duplicate keys.
Keep tests isolated
Pick one isolation strategy and apply it to every test. The common choices are compared below.
| Strategy | How it works | Trade-off |
|---|---|---|
| Transaction rollback | Each test opens a transaction and rolls it back at the end. | Fast, but code that commits its own transactions escapes the rollback. |
| Truncate between tests | A hook empties the tables before or after each test. | Simple and works with any code, but slower on large schemas. |
| Database per worker | Each parallel test worker creates its own database. | Allows parallel runs, but needs extra setup code. |
Here is a truncate hook, written for Node with the pg package and a Jest-style beforeEach:
const { Pool } = require("pg");
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
beforeEach(async () => {
await pool.query("TRUNCATE users, orders RESTART IDENTITY CASCADE");
});
afterAll(async () => {
await pool.end();
});RESTART IDENTITY resets auto-increment counters, so tests that assert on generated IDs behave the same on every run. CASCADE also empties tables that reference the listed ones. Do not truncate your seeded reference tables, or the seed data will disappear after the first test.
Where isolation fits in the run
The container, migrations, and seed run once per job. The clean-and-test cycle repeats for every test.
Common mistakes
- Migrating in a step that runs before the health check passes. Fix the readiness configuration instead of adding
sleep. - Relying on test order. If a test passes only after another test creates a row, it will fail when run alone.
- Using
POSTGRES_DBin the service but a different database name inDATABASE_URL.
Exercise
Your seed script inserts roles into a roles table. A teammate adds TRUNCATE roles CASCADE to the per-test cleanup hook, and now tests that need an "admin" role fail after the first test. Why, and what are two ways to fix it?
Show answer
The hook deletes the seeded rows after the first test, and the seed step runs only once per job. Fix it by removing roles from the truncate list so reference data stays, or by re-running the seed in the hook (or having each test create the role it needs).