如何在 RSpec 测试中禁用 MySQL 唯一约束 [英] How can I disable MySQL unique constraints in a RSpec test
本文介绍了如何在 RSpec 测试中禁用 MySQL 唯一约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为一个脚本运行规范,该脚本将统一给定的表.
I'm trying to run a spec for a script that will uniquify a given table.
我现在在迁移中有独特的约束,所以我很难创建重复项来测试我的脚本.
I now have the unique constraints in my migrations so I'm having a hard time creating duplicates to test my script.
我目前的规格是这样的.
My current specs looks like that.
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')
我错过了什么吗?
推荐答案
可能需要有人确认这一点.
Someone may need to confirm this.
SET unique_checks=0;
不是全局操作.如果你想让它工作,那么你必须这样写:
SET unique_checks=0;
is not a global operation. If you'd want this to work then you'd have to write it like that:
ActiveRecord::Base.connection.execute <<-SQL
SET unique_checks=0;
INSERT INTO <table_name> VALUES ....
SET unique_checks=1;
SQL
或者您可以删除唯一索引,创建记录,然后重新创建索引.
Or you could drop the unique index, create the records and re-create the index afterwards.
这篇关于如何在 RSpec 测试中禁用 MySQL 唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文