1

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

but It keeps on failing on

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

Am I missing something?

2
  • 1
    I'd have to ask, why would you need to have/test functionality that uniquifies records in a table where duplicate records cannot be created? Commented Oct 6, 2015 at 19:43
  • 1
    Because it was not the case before. I'm adding a migration to add a constraint but I need to run the script first to remove the duplicates. My specs starts by running all migrations so they run the one that adds the constraint and that point I can't create bad data to test my script. Commented Oct 6, 2015 at 20:05

1 Answer 1

1

Someone may need to confirm this.

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.