Skip to content
Latchkey

ActiveRecord::StatementInvalid in CI

A SQL statement issued by ActiveRecord was rejected by the database. The most common CI cause is a schema that does not match the migrations - a column or table the code expects is missing on the test database.

What this error means

A test fails with StatementInvalid wrapping the adapter error (UndefinedColumn, UndefinedTable, or a type error). The query is correct against the latest schema but the CI database is behind it.

rails
ActiveRecord::StatementInvalid:
       PG::UndefinedColumn: ERROR:  column users.last_seen_at does not exist
       LINE 1: SELECT "users".* FROM "users" WHERE "users"."last_seen_at"...

Common causes

Schema behind the migrations

A migration adding the column/table was not applied to the test database, so the query references something that does not exist yet.

Stale schema cache

A cached schema.rb or schema_cache.yml is older than the migrations, so loading it omits new columns.

Adapter-specific SQL

Raw SQL or a function works on one database but not the one CI runs, producing a syntax or type error.

How to fix it

Bring the test schema current

Reload or migrate the schema so it matches the code.

Terminal
RAILS_ENV=test bin/rails db:prepare
# if a stale cache is involved:
RAILS_ENV=test bin/rails db:schema:load

Fix the schema source or SQL

  1. Confirm schema.rb/structure.sql is committed and current.
  2. Regenerate the schema cache if you use one.
  3. For raw SQL, use database-agnostic constructs or branch on the adapter.

How to prevent it

  • Run db:prepare in CI so the schema matches the code.
  • Keep schema.rb/structure.sql committed and current.
  • Avoid adapter-specific raw SQL unless the database matches across environments.

Related guides

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