Skip to content
Latchkey

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.

bundler
ActiveRecord::NoDatabaseError: connection to server at "127.0.0.1", port 5432 failed:
FATAL:  database "app_test" does not exist

Common 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

  1. Add a Postgres service container with a health check.
  2. Point DATABASE_URL or database.yml at that host and port.
  3. Run db:prepare before the tests to create and load the schema.
.github/workflows/ci.yml
services:
  postgres:
    image: postgres:16
    env: { POSTGRES_PASSWORD: postgres }
    ports: ['5432:5432']
    options: >-
      --health-cmd "pg_isready" --health-interval 10s --health-retries 5

Create the test database before running specs

Prepare the schema so NoDatabaseError cannot occur on first connect.

Terminal
bundle exec rails db:prepare RAILS_ENV=test

How 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.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →