2012-11-21 2 views
5

세 번째 모델과의 연관성이있는 두 번째 모델에 대한 연결이있는 모델에 대한 팩토리를 가지고있을 때 빌드 전략을 유지할 수 있습니까?FactoryGirl은 중첩 된 연결을 사용하여 전략을 구축합니다.

아래 예에서 게시물은 사용자와 연결되어 있고 사용자는 도시와 연결되어 있습니다. 모든 연결에 :strategy => :build이 사용 된 경우에도 post.userpost.user.city이 데이터베이스에 저장됩니다. 신속한 테스트 스위트를 위해 이러한 데이터베이스 쓰기가 발생하지 않도록 할 수 있습니까?

Factory.define do 
    factory :user do 
    name "A User" 
    association :city, :strategy => :build 
    end 

    factory :city do 
    name "A City" 
    end 

    factory :post do 
    title "A Post" 
    body "Some text here" 
    association :user, :strategy => :build 
    end 
end 

post = FactoryGirl.build(:post) 

post.new_record?   # True 
post.user.new_record?  # False 
post.user.city.new_record? # False 

답변

2

대체 블록 구문을 사용해 보셨습니까?

Factory.define do 
    factory :user do 
    name "A User" 
    city { |city| city.association :city, :strategy => :build } 
    end 

    factory :city do 
    name "A City" 
    end 
end 
0

그것은 v4.8.0에서 구성 옵션으로 use_parent_strategy을 추가 (이전 FactoryGirl) FactoryBot 것 같습니다.

FactoryGirl.use_parent_strategy = true 

factory_bot의 repo에 관련 끌어 오기 요청 : https://github.com/thoughtbot/factory_bot/pull/961

그것은 기본적으로 해제되어, 당신의 spec/rails_helper에 다음은에 추가 켭니다
관련 문제