1

I'm trying to create a parent model with a certain number of children.

The associations are set up like this:

search_keyword_url has_many :competitors

competitor belongs_to :search_keyword_url 

My FactoryGirl definitions are:

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

These two are working just fine when used individually. I also need a factory that would associate the parent with 5 children. I've come up with this:

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

But when I try to create an url_with_5_competitors in my test:

create(:url_with_5_competitors)

... I receive the following error:

Failure/Error: create(:url_with_5_competitors) ActiveRecord::AssociationTypeMismatch: SearchKeywordUrl(#35692) expected, got # < Class:0xd351f72>(#35694)

Any help would be greatly appreciated.

4

2 回答 2

1

How about using build_list instead?

factory :url_with_5_competitors, :parent => :search_keyword_url do |search_keyword_url|
    competitors { build_list :competitor, 5 }
end
于 2013-11-05T02:53:27.703 回答
1

You might prefer this syntax with traits:

  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

usage

create(:url, :with_5_competitors)
于 2013-11-05T07:36:50.843 回答