Skip to content
Latchkey

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_URL to 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 test

Gotchas

  • 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

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