1

我正在以下 Sequel 模型上使用 DatabaseCleaner 运行 RSpec 测试

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

当我运行测试时,我收到以下错误:

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`))

我的 DatabaseCleaner 设置是:

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

DatabaseCleaner 应该在截断之前取消设置外键约束,就像使用 ActiveRecord 一样,它工作正常。

我的问题是:这是 DatabaseCleaner-Sequel 错误还是与我使用 Sequel many_through_many 插件有关?

4

1 回答 1

1

好的,这是DatabaseCleaner 的一个未解决问题。解决方法是在截断之前禁用引用键约束,然后重新启用它们。

使用 MySQL 将是这样的:

DB.run('SET FOREIGN_KEY_CHECKS=0;')
DatabaseCleaner.clean_with(:truncation)
DB.run('SET FOREIGN_KEY_CHECKS=1;')
于 2017-02-24T11:26:11.553 回答