2010-11-30 10 views
11

ファクトリーガール/マシニストの工場には、テストケース中に同じファクトリ名のオブジェクトを1回だけ作成し、常に同じインスタンスを返すような設定がありますか?私は知っている、私は何かのようにすることができます: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 

あなたはまだプラットフォームのテストプラットフォーム "との製品を作成するための標準的な製品の工場「製品」を使用することができますが、あなたはプラットフォーム名がなるように設定されている場合(第二製品を作成するには、それを呼び出したとき、それは失敗しますユニーク)。

+0

より詳細な回答、上記のより完全な説明を含むが、プラスキュウリを使用している場合の代替ソリューション: 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 Rails 4、League.where(:id => id).first_or_create - 情報を設定する必要があるbefore_saveがある場合は、find_or_initialize_by_idまたはfirst_or_iniを使用することができます試合する –