ActiveRecord::NoDatabaseError / PG::ConnectionBad in CI
Rails tried to connect to the test database and could not: either the database does not exist yet (NoDatabaseError) or the server is unreachable (PG::ConnectionBad). In CI this usually means the Postgres service container or its host/port config is wrong.
What this error means
Tests or db:prepare fail with "ActiveRecord::NoDatabaseError: FATAL: database \"app_test\" does not exist" or "PG::ConnectionBad: could not connect to server: Connection refused" pointing at localhost:5432.
ActiveRecord::NoDatabaseError: connection to server at "127.0.0.1", port 5432 failed:
FATAL: database "app_test" does not existCommon causes
The database was never created in CI
The job did not run db:create / db:prepare, so the test database does not exist when ActiveRecord connects.
Host, port, or service container mismatch
The app points at a host/port the Postgres service does not listen on, or the service container was not declared, so the connection is refused.
How to fix it
Declare the service and prepare the database
- Add a Postgres service container with a health check.
- Point DATABASE_URL or database.yml at that host and port.
- Run db:prepare before the tests to create and load the schema.
services:
postgres:
image: postgres:16
env: { POSTGRES_PASSWORD: postgres }
ports: ['5432:5432']
options: >-
--health-cmd "pg_isready" --health-interval 10s --health-retries 5Create the test database before running specs
Prepare the schema so NoDatabaseError cannot occur on first connect.
bundle exec rails db:prepare RAILS_ENV=testHow to prevent it
- Run db:prepare in the test environment before specs.
- Wait on the database service health check before connecting.
- Keep DATABASE_URL aligned with the service host and port.