Skip to content
Latchkey

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_URL for 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 tests

Gotchas

  • 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

Run this faster and cheaper on Latchkey managed runners. Start free →