user
user

Reputation: 1381

Duplicate key value violates unique constraint during rspec

How to avoid Duplicate key value violates unique constraint

i assume that id:1 already in use, but i need to strongly setup id,

because i have method in category model

def iconic
  case self.id
      when 1
       smth
     ....
  end  
 end

my factory

FactoryGirl.define do
  factory :category do
    sequence(:title) { |n| Faker::Hipster.word+"#{n}" }
    position 1
    text Faker::Lorem.sentence
    image File.open(Rails.root.join('test', 'assets', 'images', 'banners', (1..6).to_a.sample.to_s+'.png'))

  end
end

Failure/Error: c1 = create(:category, id: 1)

 ActiveRecord::RecordNotUnique:
   PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "categories_pkey"
   DETAIL:  Key (id)=(1) already exists.

Upvotes: 0

Views: 2317

Answers (1)

Jagdeep Singh
Jagdeep Singh

Reputation: 4920

Yes the problem is that you are trying to create multiple records with same value of id attribute, which is not allowed. It should always be unique.

The actual problem what i think is your model code which is dependent on id of the object.

def iconic
  case self.id
    when 1
     smth
     ....
  end  
end

This is not a good practice to write logic based on id attribute because when you can't make sure that the same id will be assigned to same object everytime you populate database. Instead you should use some other unique attributes like slug, email, username, whatever suits your model. So, you should modify you model logic like this:

def iconic
  case self.slug_or_any_other_unique_field
    when 'expected_value_of_above_field'
      smth
      ....
  end  
end

Upvotes: 1

Related Questions