2016-07-26 60 views
1

我創建了工廠客戶端和合同。我運行測試,但顯示錯誤FactoryGirl :: AttributeDefinitionError:屬性已定義:用戶

FactoryGirl.define do 
    factory :client, class: User do 
    role 'client' 
    first_name 'John' 
    sequence(:last_name) { |n| "client#{n}" } 
    sequence(:email) { |n| "client#{n}@example.com" } 
    # avatar { Rack::Test::UploadedFile.new(File.join(Rails.root, 'public', 'images', '128.jpg')) } 
    password 'password' 
    password_confirmation 'password' 
    end 
end 

支持/ controller_macros.rb

module ControllerMacros 
    def login_client 
    before do 
     @client = create(:client) 
     #@request.env['devise.mapping'] = Devise.mappings[:client] 
     sign_in @client 
    end 
    end 
end 

FactoryGirl.define do 
    factory :contract do 
    sequence(:title) { |n| "translation#{n}" } 
    amount 150 
    additional_information 'X' * 500 
    due_date { 21.days.from_now } 

    association :user, factory: :client 
    association :user, factory: :contractor 
    end 
end 

我運行測試 rspec的規格/控制器/ contracts_controller_spec.rb

require 'rails_helper' 

describe ContractsController do 
    login_client 
    let(:contract) { create(:contract) } 

    describe 'POST #create' do 

    context 'with valid attributes' do 
     it 'redirects to payment page' do 
     post :create, contract: attributes_for(:contract) 
     expect(response).to redirect_to payment_new_path 
     end 
    end 
    end 
end 

錯誤顯示:

Failure/Error: post :create, contract: attributes_for(:contract) 
    FactoryGirl::AttributeDefinitionError: 
    Attribute already defined: user 

工廠或測試有什麼問題?

+1

什麼是工廠':contract'? –

+0

我更新了問題。 – Dmitrij

+0

不太明白'association:user'的定義兩次,能否詳細說明一下? – kasperite

回答

2

工廠:contract定義了兩個屬性user,這是不允許的。

給他們獨特的標籤(工廠內),例如:

FactoryGirl.define do 
    factory :contract do 
    sequence(:title) { |n| "translation#{n}" } 
    amount 150 
    additional_information 'X' * 500 
    due_date { 21.days.from_now } 

    association :client, factory: :client 
    association :contractor, factory: :contractor 
    end 
end 

,當他們似乎裝修,我選擇與工廠名稱對應的屬性名稱。這允許甚至縮短這一點,通過留出工廠名稱:

FactoryGirl.define do 
    factory :contract do 
    sequence(:title) { |n| "translation#{n}" } 
    amount 150 
    additional_information 'X' * 500 
    due_date { 21.days.from_now } 

    client 
    contractor 
    end 
end 

(見http://www.rubydoc.info/gems/factory_girl/file/GETTING_STARTED.md,部分 「關聯」:

If the factory name is the same as the association name, the factory name can be left out.