ActiveRecord::InvalidForeignKey error when testing

I was getting this error when running my tests, but everything seemed OK in development:

PG::ForeignKeyViolation: ERROR: update or delete on table “users” violates foreign key constraint “transactions_user_id_fk” on table “transactions” (ActiveRecord::InvalidForeignKey)
DETAIL: Key (id)=(1) is still referenced from table “transactions”.
: DELETE FROM “users”;

This was related to database permissions and the DatabaseCleaner gem.

DatabaseCleaner wants to disable all referential integrity before and after every test, so that it can quickly delete everything in the database without worrying about foreign keys. A quick tail -n 50 log/test.log showed that the database user does not have permission to do that, thus the error:

(42.1ms) ALTER TABLE “schema_migrations” DISABLE TRIGGER ALL;ALTER TABLE “delayed_jobs” DISABLE TRIGGER ALL;ALTER TABLE “users” DISABLE TRIGGER ALL;ALTER TABLE “stocks” DISABLE TRIGGER ALL;ALTER TABLE “transactions” DISABLE TRIGGER ALL
PG::InsufficientPrivilege: ERROR: permission denied: “RI_ConstraintTrigger_a_362782” is a system trigger

The (short term) solution was to make the database user a superuser, which seems OK since this is only needed in the test environment, and not in Production. (In production it would be a security vulnerability). I may ask around if this is a good long term solution, or if there is some better way to deal with this.

Advertisements

One thought on “ActiveRecord::InvalidForeignKey error when testing

  1. Wow, you just saved me some couple hours of debugging. Because I had the same problem but did NOT get an InsufficientPrivilege error that would tell me where to look for. I switched to the :transaction strategy in DatabaseCleaner and my specs where green.

    Thank you so much!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s