2013-08-02 2 views
0

유효성 검사 연관이있는 객체와 표준 has_many 관계가 있습니다. 하지만 오류 스택 수준을 너무 깊이 피하는 방법을 모르겠습니다. 여기FactoryGirl + Rspec 연관성 검증 has_many

내 두 모델 여기

class Address < ActiveRecord::Base 
belongs_to :employee, :inverse_of => :addresses 
end 

class Employee < ActiveRecord::Base 

    has_many :addresses, :dependent => :destroy, :inverse_of => :employee  #inverse of  can use addresses.employee 
    has_many :typings 
    has_many :types, through: :typings 

    validates :addresses, length: { minimum: 1 } 
    validates :types, length: { minimum: 1 } 


end 

내 공장 여기

FactoryGirl.define do 
factory :address, class: Address do 
    address_line 'test' 
    name 'Principal' 
    city 'test' 
    zip_code 'test' 
    country 'france' 
end 
end 

FactoryGirl.define do 
factory :employee_with_address_type, class: Employee do |e| 
    e.firstname 'Jeremy' 
    e.lastname 'Pinhel' 
    e.nationality 'France' 
    e.promo  '2013' 
    e.num_mobile 'Test' 
    e.types { |t| [t.association(:type)] } 
    after :build do |em| 
    em.addresses << FactoryGirl.build(:address) 
    end 
end 
end 

내 모델 테스트

describe Address do 
    context 'valid address' do 
    let(:address) {FactoryGirl.build(:address)} 
    subject {address} 

    #before(:all) do 
    # @employee = FactoryGirl.build(:employee_with_address_type) 
    #end 

    it 'presence of all attributes' do 
    should be_valid 
    end 
end 
end 

누군가 나에게이 문제를 해결하는 방법을 이해하는 데 도움이 될 수 있습니다? 나는 성공없이 내 공장과 다른 조합을 시도.

편집 : 내가 무슨 짓을

 FactoryGirl.define do 
     factory :address_with_employee, class: Address do 
     address_line 'test' 
     name 'Principal' 
     city 'test' 
     zip_code 'test' 
     country 'france' 
     association :employee, :factory => :employee_with_address_type 
     after :build do |ad| 
      ad.employee.addresses << ad 
     end 
     end 
    end 

    FactoryGirl.define do 
     factory :employee_with_address_type, class: Employee do |e| 
     e.firstname 'Jeremy' 
     e.lastname 'Pinhel' 
     e.nationality 'France' 
     e.promo  '2013' 
     e.num_mobile 'Test' 
     e.types { |t| [t.association(:type)] } 
     end 
    end 

그냥 직원의 주소로 직접 만든 주소 인스턴스를 추가하고 다음과 같이

class Employee < ActiveRecord::Base 

    has_many :addresses, :dependent => :destroy, :inverse_of => :employee  #inverse of  can use addresses.employee 
    has_many :typings 
    has_many :types, through: :typings 

    validates_associated :addresses 
    validates_associated :types 


end 
+1

예외를 게시 할 수 있습니까? – unnu

+0

여기 내 예외 오류/오류 : be_valid 오류가 있어야합니다 : 직원을 비워 둘 수 없으며 연관을 추가하는 경우 : 내 주소 팩토리의 직원이 스택 수준이 너무 높음 – Pinou

답변

0

당신은 당신의 공장을 다시 작성할 수 있습니다. 이 후 빌드 루프에서 물론 같은 직원과 추가 주소를 만들고 목록에 추가 할 수 있습니다.

+0

감사합니다.이 솔루션을 이해했지만 실패했습니다. -> 내 Employee 모델의 주소에 대한 유효성 검사가 있으므로 주소는 비워 둘 수 없습니다. 어떻게 해결할 수 있을까요? – Pinou

+0

필자는 주소를 valides_associated의 주소로 바꾸 었으며 이제는 테스트가 좋습니다. – Pinou