2013-07-13 3 views
5

J'utilise l'exemple FactoryGirl pour les relations has_many de http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl. Plus précisément, l'exemple est:FactoryGirl has_many association

Modèles:

class Article < ActiveRecord::Base 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :article 
end 

usines:

factory :article do 
    body 'password' 

    factory :article_with_comment do 
    after_create do |article| 
     create(:comment, article: article) 
    end 
    end 
end 

factory :comment do 
    body 'Great article!' 
end 

Quand je lance ce même exemple (avec le schéma approprié, bien sûr), une erreur est renvoyée

Y at-il une nouvelle façon de créer des modèles avec has_many associations avec FactoryGirl?
2.0.0p195 :001 > require "factory_girl_rails" 
=> true 
2.0.0p195 :002 > article = FactoryGirl.create(:article_with_comment) 
ArgumentError: wrong number of arguments (3 for 1..2) 

Répondre

1

À partir d'aujourd'hui votre exemple serait ressemble à ceci:

factory :article do 
    body 'password' 

    factory :article_with_comment do 
    after(:create) do |article| 
     create_list(:comment, 3, article: article) 
    end 
    end 
end 

factory :comment do 
    body 'Great article!' 
end 

Ou si vous avez besoin de flexibilité sur un certain nombre de commentaires:

factory :article do 
    body 'password' 

    transient do 
    comments_count 3 
    end 

    factory :article_with_comment do 
    after(:create) do |article, evaluator| 
     create_list(:comment, evaluator.comments_count, article: article) 
    end 
    end 
end 

factory :comment do 
    body 'Great article!' 
end 

utilisez ensuite comme

create(:article_with_comment, comments_count: 15) 

Pour plus de détails s'il vous plaît se référer à la section des associations dans le guide de démarrage: https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations

Questions connexes