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.
ActiveRecord::StatementInvalid: PG::UndefinedTable: relation "users" does not exist
# worker database myapp_test-1 was created but never schema-loadedCommon 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
- Run
db:schema:load(or db:prepare) so the primary test DB has all tables. - Let
parallelizecreate the worker databases from it during setup. - Grant the DB user permission to create databases in CI.
- run: bin/rails db:test:prepare
env:
RAILS_ENV: testUse a privileged CI database user
Run tests as a user that can create databases so per-worker copies succeed.
env:
DATABASE_URL: postgres://postgres:postgres@localhost:5432/myapp_testHow 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.