2013-07-13 12 views
5

मैं has_manyhttp://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl से संबंधों के लिए फैक्टरीगर्ल उदाहरण का उपयोग कर रहा हूं। विशेष रूप से, उदाहरण है:फैक्टरीगर्ल has_many एसोसिएशन

मॉडल:

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) 

क्या फैक्टरीगर्ल के साथ 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

संबंधित मुद्दे