The error:ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry 'FakeRecord-1' for key 'index_entities_on_entityable'
I have a table with a polymorphic unique relationship:
create_table :entities do |t|
t.references :entityable, null: false, polymorphic: true, index: { unique: true }
end
I've implemented the logic for this relationship in a Concern (called Entityable). This involves creating an associated Entity automatically on creation of a model which includes Entityable:
before_validation -> { Entity.create!(entityable: self) if entity.nil? }, on: :create
I'm using with_model to test this Concern outside of an existing model:
class EntityableTest < ActiveSupport::TestCase
with_model :FakeRecord do
table do |t|
t.string :name
end
model do
include Concerns::Entityable
end
end
def test_something
record = FakeRecord.create!(name: 'test')
# assert that this creates an Entity correctly...
end
end
Here, the test passes on the first run, but on subsequent runs, calling FakeRecord.create! gives the error ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry 'FakeRecord-1' for key 'index_entities_on_entityable'. It seems that what's happening is a FakeRecord with ID of 1 is trying to be created, and an index entry already exists for that.
This is strange to me for 2 reasons:
I know that when creating regular ActiveRecord models, the IDs are incremented even between test runs, so this issue doesn't occur.
I would think that indexes are cleared out between runs similar to how tables are, but maybe this is not the case.
Regardless, it would seem that the fix for this would be incrementing model IDs rather than restarting from 1 each time. In the meantime, it seems impossible to effectively test unique indexes via with_model.
Please let me if there is any need for clarification. Thanks!
The error:
ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry 'FakeRecord-1' for key 'index_entities_on_entityable'
I have a table with a polymorphic unique relationship:
I've implemented the logic for this relationship in a Concern (called
Entityable
). This involves creating an associatedEntity
automatically on creation of a model which includesEntityable
:I'm using with_model to test this Concern outside of an existing model:
Here, the test passes on the first run, but on subsequent runs, calling
FakeRecord.create!
gives the errorActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry 'FakeRecord-1' for key 'index_entities_on_entityable'
. It seems that what's happening is aFakeRecord
with ID of1
is trying to be created, and an index entry already exists for that.This is strange to me for 2 reasons:
Regardless, it would seem that the fix for this would be incrementing model IDs rather than restarting from
1
each time. In the meantime, it seems impossible to effectively test unique indexes viawith_model
.Please let me if there is any need for clarification. Thanks!