Casecommons / with_model

Dynamically build an Active Record model (with table) within a test context
http://www.casebook.net
MIT License
167 stars 18 forks source link

Non-incrementing IDs cause problems with unique indexes #51

Open gcpreston opened 6 months ago

gcpreston commented 6 months ago

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:

  1. I know that when creating regular ActiveRecord models, the IDs are incremented even between test runs, so this issue doesn't occur.
  2. 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!