2013-07-13 12 views
5

has_many関係のFactoryGirlの例はhttp://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girlです。具体的には、例です。FactoryGirl has_many association

モデル:

class Article < ActiveRecord::Base 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :article 
end 

工場:

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 

私は同じ例(適切なスキーマを持つが、もちろん)は、エラーがスローされていることを実行します

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) 

FactoryGirlとの関連付けをhas_manyで行うモデルを作成する新しい方法はありますか?

答えて

1

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 

それとも、コメントの数に柔軟性が必要な場合:更なるガイダンスはこちら団体に関するセクションを見てくださいその後

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 

のように使用します

詳細については、スタートガイドの関連セクションを参照してください。 https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations

関連する問題