require 'rails_helper'
require 'duplicate_remover'

describe DuplicateRemover do
  before(:all) do
    Temping.create :person do
      validates :name, uniqueness: true

      with_columns do |t|
        t.string :name
      end
    end
  end
  
  after(:all) do
    Temping.teardown
  end

  context 'when record attribute is unique' do
    it 'does not update the record' do
      person = create_person("Jane")

      DuplicateRemover.new(person, :name).perform!

      expect(person.name).to eq("Jane")
    end
  end

  context 'when record attribute is a duplicate' do
    it 'updates the record with a unique name' do
      create_person("Jane")
      person = create_person("Jane")

      DuplicateRemover.new(person, :name).perform!

      expect(person.name).to eq("Jane (2)")
    end
  end

  context 'when record attribute is a duplicate multiple times' do
    it 'updates the record with a unique name' do
      create_person("Jane")
      create_person("Jane (2)")
      create_person("Jane (3)")
      person = create_person("Jane")

      DuplicateRemover.new(person, :name).perform!

      expect(person.name).to eq("Jane (4)")
    end
  end

  private

  def create_person(name)
    Person.new(name: name) do |person|
      person.save(validate: false)
    end
  end
end
