How to Run Database Migrations Before Tests in GitHub Actions
Run your migration command as a dedicated step before the test step so the schema exists before any test queries it.
After the database service is healthy, run the project migration command (Prisma, Knex, Rails, Django, etc.) against the CI DATABASE_URL, then run tests. Keeping migration and test in the same job avoids cross-job database handoff.
Steps
- Start the database as a service with a health check.
- Run the migration command before the test command.
- Use the same
DATABASE_URLfor migrate and test.
Workflow
.github/workflows/ci.yml
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-retries 5
env:
DATABASE_URL: postgres://postgres:postgres@localhost:5432/app_test
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npx prisma migrate deploy # apply migrations
- run: npm test # then run testsGotchas
- Use the deploy/apply command (
migrate deploy,db:migrate), not the interactive dev command that may prompt or create new migrations. - If tests reset the schema themselves, run migrations once and let the suite truncate rather than re-migrating per test.
Related guides
How to Seed a Test Database in GitHub ActionsLoad fixture data into the CI database after migrations and before tests in GitHub Actions, so integration te…
How to Run Prisma Migrations in GitHub ActionsApply Prisma migrations in GitHub Actions with prisma migrate deploy against the CI database, the non-interac…
How to Run Database Migrations Before Deploy in GitHub ActionsRun database migrations as a gating job before the deploy in GitHub Actions, so the new schema is in place fi…