Reputation: 3483
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).
Upvotes: 0
Views: 6346
Reputation: 12592
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.
I cleaned the DB and generated schema from schema.rb
instead of running whole migration.
bin/rake db:reset RAILS_ENV=test
Upvotes: 1
Reputation: 13077
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)
Upvotes: 4