2013-07-13 15 views
5

Sto utilizzando l'esempio FactoryGirl per le relazioni has_many da http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl. In particolare, l'esempio è:FactoryGirl has_many association

Modelli:

class Article < ActiveRecord::Base 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :article 
end 

Fabbriche:

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 

Quando eseguo quello stesso esempio (con il corretto schema, naturalmente), viene generato un errore

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) 

C'è un nuovo modo per creare modelli con le associazioni has_many con FactoryGirl?

risposta

1

Ad oggi il tuo esempio sarebbe simile a questo:

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 

O se avete bisogno di flessibilità su una serie di osservazioni:

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 

Quindi utilizzare come

guida

Per maggiori dettagli si rinvia alla Sezione associazioni a iniziare: https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations

Problemi correlati