我正在尝试创建一个包含一定数量子项的父模型。
关联设置如下:
search_keyword_url has_many :competitors
competitor belongs_to :search_keyword_url
我的FactoryGirl定义是:
FactoryGirl.define do
factory :url, :class => SearchKeywordUrl, aliases: [:search_keyword_url] do
user
sequence(:url) {|n| "http://example#{n}.com"}
end
factory :competitor do
search_keyword_url
sequence(:url) {|n| "http://competitor#{n}.com"}
end
end
单独使用时,这两个工作正常。我还需要一个工厂,将父母与5个孩子联系起来。我想出了这个:
factory :url_with_5_competitors, :parent => :search_keyword_url do |search_keyword_url|
search_keyword_url.after_create { |sku| 5.times { create(:competitor, :search_keyword_url => sku ) } }
end
但是当我尝试在我的测试中创建url_with_5_competitors时:
create(:url_with_5_competitors)
...我收到以下错误:
失败/错误:创建(:url_with_5_competitors) ActiveRecord的:: AssociationTypeMismatch: SearchKeywordUrl(#35692)期待,得到#<类:0xd351f72>(#35694)
非常感谢任何帮助。
答案 0 :(得分:1)
如何使用build_list
呢?
factory :url_with_5_competitors, :parent => :search_keyword_url do |search_keyword_url|
competitors { build_list :competitor, 5 }
end
答案 1 :(得分:1)
您可能更喜欢这种语法:[/ p>
factory :url, :class => SearchKeywordUrl, aliases: [:search_keyword_url] do
user
sequence(:url) {|n| "http://example#{n}.com"}
trait :with_5_competitors do
competitors { build_list :competitor, 5 }
end
end
create(:url, :with_5_competitors)