Skip to content
Latchkey

Rails parallel tests database connection error in CI

Rails parallelize runs tests across worker processes, each using its own database suffixed with the worker number. In CI these per-worker databases fail to connect when the base test database is not schema-loaded or the DB user cannot create the worker copies.

What this error means

Parallel test runs fail with a connection error naming a worker database like "myapp_test-1" that does not exist, or "PG::InsufficientPrivilege" while creating it.

Rails
ActiveRecord::StatementInvalid: PG::UndefinedTable: relation "users" does not exist
# worker database myapp_test-1 was created but never schema-loaded

Common causes

Worker databases are not schema-loaded

parallelize creates per-worker databases from the primary test database; if the primary has no schema, the copies are empty too.

The DB user cannot create databases

Creating worker databases needs CREATEDB privilege; a restricted CI user hits a privilege error.

How to fix it

Load the schema before parallel setup

  1. Run db:schema:load (or db:prepare) so the primary test DB has all tables.
  2. Let parallelize create the worker databases from it during setup.
  3. Grant the DB user permission to create databases in CI.
.github/workflows/ci.yml
- run: bin/rails db:test:prepare
  env:
    RAILS_ENV: test

Use a privileged CI database user

Run tests as a user that can create databases so per-worker copies succeed.

.github/workflows/ci.yml
env:
  DATABASE_URL: postgres://postgres:postgres@localhost:5432/myapp_test

How to prevent it

  • Schema-load the primary test DB before parallelize runs.
  • Give the CI database user CREATEDB privileges.
  • Keep PARALLEL_WORKERS reasonable for the runner size.

Frequently asked questions

What causes "parallelize + separate test DBs"?
parallelize creates per-worker databases from the primary test database; if the primary has no schema, the copies are empty too.
How do I fix parallelize + separate test DBs?
Load the schema before parallel setup

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card