"Name has already been taken" 在 RSpec/FactoryGirl 中有多个关联

"Name has already been taken" in RSpec/FactoryGirl with multiple associations

我正在尝试 运行 一个非常基本的规范测试,但失败并显示错误“名称已被占用”。

Update 属于 User,他有很多 Roles.

用户型号

# == Schema Information
#
# Table name: users
#
#  id                     :integer          not null, primary key
#  email                  :string           default(""), not null
#

FactoryGirl.define do
  factory :user_engineer, class: User do
    id 1
    email 'someone@somewhere.com'
    roles {[FactoryGirl.create(:engineer)]}
  end
end

角色模特

# == Schema Information
#
# Table name: roles
#
#  id          :integer          not null, primary key
#  name        :string
#  description :text
#

FactoryGirl.define do
  factory :engineer, class: Role do
    id 3
    name 'Engineer'
    description 'He is the chosen one'
  end
end

更新模型

# == Schema Information
#
# Table name: updates
#
#  id            :integer          not null, primary key
#  content       :text
#  user_id       :integer
#  ticket_id :integer
#

FactoryGirl.define do
  factory :update do
    content "This is a test update"
    association :user, factory: :user_engineer
  end
end

update_spec.rb

require 'rails_helper'

RSpec.describe Update, type: :model do
  let(:update){ FactoryGirl.create :update }
  it { expect(update).to be_valid }
end

这是错误:

Update
  example at ./spec/models/update_spec.rb:19 (FAILED - 1)

Failures:

  1) Update 
     Failure/Error: roles {[FactoryGirl.create(:engineer)]}

     ActiveRecord::RecordInvalid:
       Validation failed: Name has already been taken

我怎样才能通过测试?!

EDIT: 通过添加建议的序列行,在 运行ning RAILS_ENV=test rake db:drop:

之后出现以下错误
1) Update 
     Failure/Error: roles {[FactoryGirl.create(:engineer)]}

     ActiveRecord::RecordNotUnique:
       PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "roles_pkey"
       DETAIL:  Key (id)=(3) already exists.
       : INSERT INTO "roles" ("id", "name", "description", "created_at", "updated_at") VALUES (, , , , ) RETURNING "id"

为用户模型尝试以下代码

FactoryGirl.define do
  factory :user_engineer, class: User do
    id 1
    email 'someone@somewhere.com'
    roles {[FactoryGirl.create(:engineer, name: "new_engineer")]}
  end
end

由于name属性有uniq约束,我想你的测试数据库中已经有一条工程师记录是你第一次添加的运行测试用例,所以最好清除测试数据库运行测试用例之前或之后。

将以下代码块放入 spec/rails_helper.rb 文件。

  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

从你的错误来看,很明显你对 name 属性进行了 uniq 验证,你应该使用 sequence 技术。

FactoryGirl.define do
  factory :engineer, class: Role do
    id 3
    sequence(:name) { |n| "Engineer-#{n}" }
    description 'He is the chosen one'
  end
end