RedFred
RedFred

Reputation: 1039

Rspec with database_cleaner on Sequel causes foreign key truncation error

I'm running RSpec tests with DatabaseCleaner on the following Sequel models

class User < Sequel::Model
      one_to_many :memberships
      many_through_many :accounts, [[:memberships, :user_id, :account_id]]
end

class Account < Sequel::Model 
      one_to_many :memberships
      many_through_many :users, [[:memberships, :user_id, :account_id]]
end

class Membership < Sequel::Model
      many_to_one :account
      many_to_one :user
end

when I run the tests, I get the following error:

An error occurred in a `before(:suite)` hook.
Failure/Error: DatabaseCleaner.clean_with(:truncation)

Sequel::DatabaseError:
  Mysql2::Error: Cannot truncate a table referenced in a foreign key constraint (`account_users`.`memberships`, CONSTRAINT `memberships_ibfk_2` FOREIGN KEY (`account_id`) REFERENCES `account_users`.`accounts` (`id`))

My DatabaseCleaner setup is:

  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
  end

DatabaseCleaner should be unsetting foreign key constraints before truncating, as it does with ActiveRecord, which works fine.

My question is: Is this a DatabaseCleaner-Sequel bug or is it something to do with my usage of the Sequel many_through_many plugin?

Upvotes: 1

Views: 2184

Answers (1)

RedFred
RedFred

Reputation: 1039

Ok, this is an open issue with DatabaseCleaner. The workaround is to disable referential key constraints before truncating and re-enabling them afterwards.

With MySQL it would be thus:

DB.run('SET FOREIGN_KEY_CHECKS=0;')
DatabaseCleaner.clean_with(:truncation)
DB.run('SET FOREIGN_KEY_CHECKS=1;')

Upvotes: 2

Related Questions