0

I am currently developpig an app with ruby on rails. I have two models: House and Platform. Platform has a reference to House:

## house.rb
class House < ApplicationRecord
  has_many :platforms, dependent: :destroy
end
## platform.rb
class Platform < ApplicationRecord
  belongs_to :house
end

On addition to that, I defined some fixtures for both models:

# houses.yml
one:
  name: Ker Maria

two:
  name: Coquelicots
# platforms.yml
one:
  name: airbnb
  url: https://www.airbnb.com
  house: one

When I launch tests (using command line: rails test test/models/house_test.rb), I get the following error:

WARNING: Rails was not able to disable referential integrity.

This is most likely caused due to missing permissions.
Rails needs superuser privileges to disable referential integrity.

    cause: PG::InsufficientPrivilege: ERROR:  permission denied: "RI_ConstraintTrigger_a_39161" is a system trigger


E

Error:
HouseTest#test_house_count:
ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR:  update or delete on table "houses" violates foreign key constraint "fk_rails_7966fa231e" on table "platforms"
DETAIL:  Key (id)=(980190962) is still referenced from table "platforms".

It seems that rails test does not like destroying my house while a platform instance is still pointing to that house. This violates platforms table's foreign key on houses table.

Could someone please help me with that error?

Note: similar question has been raised a few months ago by ASing - see Rails Test: Rails was not able to disable referential integrity. Rails needs superuser privileges to disable referential integrity on Azure Postgres

Here is what I have tried:

  • changing postgresql testing user profile (from myself to postgresql which would have admin rights and hence would overcome that error). But I failed to do that.
  • the error happens when (i) config.active_record.verify_foreign_keys_for_fixtures is set to true in config\application.rb AND (ii) I run the test for the second time in test database life. Indeed, when I set config.active_record.verify_foreign_keys_for_fixtures to false, and then run rails db:drop db:create db:migrate RAILS_ENV=test in my terminal, and then execute the tests by running rails test:models, then tests are run without any errors.
Jérôme
  • 1
  • 3
  • *Just use fixtures they said - it will be fun they said.* Jokes aside - if you're curious what `verify_foreign_keys_for_fixtures` does and why it blows up unless you have some very elevated priveledges you can check how its implemented by the postgres driver: https://github.com/rails/rails/blob/06e9fbd954ab113108a7982357553fdef285bff1/activerecord/lib/active_record/connection_adapters/postgresql/referential_integrity.rb#L41 – max Mar 22 '23 at 15:18

0 Answers0