2016-02-08 37 views
2

我正在尝试运行非常基本的规格测试,并且因错误“名称已被占用”而失败。RSpec/FactoryGirl中有多个关联的“名称已被占用”

更新属于用户谁拥有许多角色

用户模型

# == 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 '[email protected]' 
    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 

我怎样才能通过测试?

编辑:通过添加序列行我建议,我得到的运行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 ($1, $2, $3, $4, $5) RETURNING "id" 
+0

你可以只运行这个'{expect {update(update).to be_valid}'spec,并看到错误是否到来。我认为这个错误来自其他代码的副作用。 –

+0

我应该发布哪些可以帮助调试的内容? – ftshtw

+0

好的,告诉我'it {expect {update(update)to_valid}'的行号和文件名。 –

回答

2

由于从你的错误很明显,你有一个uniq的验证上name属性,你应该再使用sequence技术。

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

我用收到的新错误更新了我的问题。 – ftshtw

0

尝试下面的代码,用户模型

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

由于是name属性的uniq约束,我认为你的测试数据库中已经有了一个工程师记录,它在第一次运行测试用例时增加了,所以最好在运行t之前或之后清楚地测试数据库est案件。

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

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

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

这对于理解错误到来为什么没有帮助。你有没有看到它的证据? –

+0

嘿,我已经更新了我的答案,请检查一下。 – Dheeresha

+0

酷,仍然是你的第一个错误的代码。而是要求OP使用_sequence_。 –