我正在尝试为将唯一化给定表的脚本运行规范。

现在,我在迁移中具有独特的约束,因此我很难创建重复项来测试脚本。

我当前的规格看起来像这样。

require 'spec_helper'

describe OneTime::UniquifyTypeDescriptorContext do

  before(:each) do
    duplicated_type_descriptor_contexts = FactoryGirl.build_list(:type_descriptor_context, 5, {:type_name => :foo})
    ActiveRecord::Base.connection.execute('SET unique_checks=0;')
    duplicated_type_descriptor_contexts.each{|tdc| tdc.save!(:validate => false)}
    ActiveRecord::Base.connection.execute('SET unique_checks=1;')
    FactoryGirl.create(:type_descriptor_context, :type_name => :bar)
  end

  context "#process!" do
    it "should remove duplicates" do
      OneTime::UniquifyTypeDescriptorContext.new.process!
      expect(TypeDescriptorContext.count).to eq 2
    end
  end
end


但它继续失败

ActiveRecord::RecordNotUnique:
       ActiveRecord::JDBCError: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'foo' for key 'index_type_descriptor_contexts_on_type_name': INSERT INTO `type_descriptor_contexts` (`created_at`, `type_name`, `updated_at`) VALUES ('2015-10-06 18:23:39', 'foo', '2015-10-06 18:23:39')


我想念什么吗?

最佳答案

可能需要确认。

SET unique_checks=0;不是全局操作。如果您想让它工作,那么就必须这样写:

ActiveRecord::Base.connection.execute <<-SQL
  SET unique_checks=0;
  INSERT INTO <table_name> VALUES ....
  SET unique_checks=1;
SQL


或者,您可以删除唯一索引,创建记录,然后再重新创建索引。

关于mysql - 如何在RSpec测试中禁用MySQL唯一约束,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32976997/

10-16 13:28