ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR: duplicate key value violates unique constraint
Asked Answered
H

2

0

I've combined my user & shift factories to save space.

FactoryGirl.define do
  factory :user do
    name 'test'
    password 'test'
    phone_number '1-444-555-8888'
  end

  factory :shift do
    user
  end
end

This is my test. Fails on 'shifts = create_list(:shift, 20)'

require 'spec_helper'

describe MyFirebase do
  let(:dummy_class) { Class.new { include MyFirebase } }
  describe ".firebase_update_duration" do
    it "should update total duration value in firebase", focus: true do
      shifts = create_list(:shift, 20)
      instance = dummy_class.new
      duration = instance.firebase_update_duration
      p "/" * 100
      p duration
      p "/" * 100
      duration.should eq(Shift.shift_duration_total)
    end
  end
end

This is the error:

Failure/Error: shifts = create_list(:shift, 20)
     ActiveRecord::RecordNotUnique:
       PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "index_users_on_phone_number"
       DETAIL:  Key (phone_number)=(1-444-555-8888) already exists.

How is there duplicate user records? I thought I was creating a list of shifts for a specific user (user one to many shifts association).

Hautesavoie answered 22/2, 2015 at 0:17 Comment(0)
C
4

The error is because create_list(:shift, 20) is trying to create 20 users, all with the same phone number 1-444-555-8888, and there is a uniqueness condition that prevents this.

Change the factory definition such that it creates unique phone numbers for each users, and the error should go away.

Here's one way to do that:

phone_number { rand(10**9..10**10)}

Reference: Use a factory's sequence to generate unique phone numbers

Since your requirement is to create 20 shifts for one user, try the following:

@user = create(:user)
create_list(:shift, 20, user: @user)
Catanzaro answered 22/2, 2015 at 0:27 Comment(0)
G
1

If the other answer does not solve your issue

In my case I had a migration file which loads some data to the table.

I ran

rake db:migrate:reset RAILS_ENV=test

to regenerate clean schema.rb file. What happened is, generated DB by running all the migration files. This caused the collision because in a test file I did like

 let!(:external_call_center_number) { create(:setting, :external_call_center_number).value }

then it started showing

 ActiveRecord::RecordNotUnique:
       PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "index_settings_on_code"

 DETAIL:  Key (code)=(EXTERNAL_CALL_CENTER_NUMBER) already exists.

Solution

I cleaned the DB and generated schema from schema.rb instead of running whole migration.

 bin/rake db:reset RAILS_ENV=test
Galegalea answered 14/6, 2021 at 4:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.