How to Seed a Test Database Before Tests with GitHub Actions
Running migrations and seed scripts before the tests gives every run a known, repeatable data state.
After the database service container is healthy, run your migration and seed commands as ordinary steps before the test step. Tests then start from deterministic fixtures rather than an empty or stale database.
Steps
- Start the database as a service container with a health check.
- Run migrations, then a seed script, as steps before the tests.
- Pass the same
DATABASE_URLto the seed and test steps.
Workflow
.github/workflows/ci.yml
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env: { POSTGRES_PASSWORD: test, POSTGRES_DB: app_test }
ports: ['5432:5432']
options: >-
--health-cmd "pg_isready -U postgres" --health-interval 10s --health-retries 5
env:
DATABASE_URL: postgres://postgres:test@localhost:5432/app_test
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm run db:migrate
- run: npm run db:seed
- run: npm testGotchas
- Seed before tests run; seeding inside a test can leak state between cases.
- Make seed scripts idempotent so a retried job does not fail on duplicate rows.
Related guides
How to Run a Test Database as a Service Container with GitHub ActionsSpin up Postgres as a GitHub Actions service container with a health check and port mapping, so your tests co…
How to Run Integration Tests with Docker Compose in GitHub ActionsStand up a multi-service stack with Docker Compose in GitHub Actions, wait for it to be healthy, run integrat…