2016-07-26 11 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

何ですか? –

+0

私は質問を更新しました。 – Dmitrij

+0

'association:user'の定義を2度理解していないのですか? – kasperite

答えて

2

工場:contractは、許可されていないuserという2つの属性を定義しています。

は彼らのユニークな(工場内)ラベル、例えばを与える:

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 

を彼らはフィッティングに見えるように、私は工場名に対応する属性名を選択しました。これは、工場名を残すことによって、でもこれを短縮することができます:contract`:

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.

) `のための工場が

関連する問題