2013-07-13 23 views
5

Tôi đang sử dụng ví dụ FactoryGirl cho các mối quan hệ has_many từ http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl. Cụ thể, ví dụ là:FactoryGirl has_many association

Models:

class Article < ActiveRecord::Base 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :article 
end 

nhà máy:

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 

Khi tôi chạy cùng ví dụ (với schema thích hợp, tất nhiên), một lỗi được ném

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ó cách nào mới để tạo mô hình với has_many liên kết với FactoryGirl không?

Trả lời

1

Tính đến hôm nay ví dụ của bạn sẽ trông như thế này:

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 

Hoặc nếu bạn cần sự linh hoạt về một số ý kiến:

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 

Sau đó sử dụng như

create(:article_with_comment, comments_count: 15) 

Để biết thêm chi tiết, vui lòng tham khảo phần liên kết trong hướng dẫn bắt đầu: https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations

Các vấn đề liên quan