如何在RSpec测试中禁用MySQL唯一约束

时间:2015-10-06 18:24:39

标签: mysql ruby-on-rails rspec

我正在尝试运行一个脚本,该脚本将统一给定的表。

我现在在迁移中遇到了独特的限制,所以我很难创建重复项来测试我的脚本。

我目前的规格看起来像那样。

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

我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

有人可能需要确认这一点。

SET unique_checks=0;不是全球运营。如果你想让它发挥作用,你就必须这样写:

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

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