2010-11-30 3 views
11

팩토리 소녀/기계 주의자의 공장에서 테스트 케이스 중에 동일한 팩토리 이름을 가진 객체를 한 번만 생성하고 항상 같은 인스턴스를 반환하도록하는 구성이 있습니까? 알아요. 다음과 같이 할 수 있습니다.factory_girl/machinist의 싱글 톤 공장입니까?

def singleton name 
    @@singletons ||= {} 
    @@singletons[name] ||= Factory name 
end 
... 
Factory.define :my_model do |m| 
    m.singleton_model { singleton :singleton_model } 
end 

하지만 더 좋은 방법이있을 수 있습니다.

답변

1

이것이 유용 할 지 확실하지 않습니다.

이 설정을 사용하면 'singleton_product'팩토리를 사용하여 n 개의 제품을 만들 수 있습니다. 이러한 모든 제품에는 동일한 플랫폼 (예 : 플랫폼 'FooBar')이 있습니다.

factory :platform do 
    name 'Test Platform' 
end 

factory :product do 
    name 'Test Product' 
    platform 

    trait :singleton do 
    platform{ 
     search = Platform.find_by_name('FooBar') 
     if search.blank? 
     FactoryGirl.create(:platform, :name => 'FooBar') 
     else 
     search 
     end 
    } 
    end 

    factory :singleton_product, :traits => [:singleton] 
end 

당신은 여전히 ​​플랫폼 '테스트 플랫폼'을 가진 제품을 만들기 위해 표준 제품 공장 '제품'을 사용할 수 있지만 플랫폼 이름이로 설정되어있는 경우 (2 제품을 만들기 위해 호출 할 때 오류가 발생합니다 독특한).

+0

더 자세한 대답은, 위의 더욱 철저한 설명을 포함하여이 플러스 Cucumber를 사용하는 대체 솔루션 : http://stackoverflow.com/questions/2015473/using-factory-girl-in-rails-with-associations-that-have-unique-constraints-gett/8343150#8343150 –

17

공장에서 initialize_with 매크로를 사용하고 개체가 이미 있는지 확인한 다음 다시 만들지 않아도됩니다. 공장은 협회에 의해 참조되는 것을 특징으로 경우에도 작동합니다

FactoryGirl.define do 
    factory :league, :aliases => [:euro_cup] do 
    id 1 
    name "European Championship" 
    owner "UEFA" 
    initialize_with { League.find_or_create_by_id(id)} 
    end 
end 

가 더 대안으로 여기에 비슷한 질문입니다 :는이 항목의 Using factory_girl in Rails with associations that have unique constraints. Getting duplicate errors

+2

With 레일즈 4에서는 League.where (: id => id)를 사용하고자합니다. .first_or_create - 정보를 설정해야하는 before_save가있는 경우 find_or_initialize_by_id 또는 first_or_ini를 원할 수 있습니다 합치다 –