2016-02-08 38 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_。 –