Putting aside arguments on whether or not you should test existence of a model's associations, I have a model called Order and I am validating that it has at least one item in its has_many association using:
class Order < ActiveRecord::Base
  has_many :items
  validates :items, presence: true
end
I have set FactoryGirl to lint my factories (checking for validity). So my order factory is not valid unless I create an item for its has_many collection.
My orders factory looks like this:
FactoryGirl.define do
  factory :order do
    ignore do
      items_count 1
    end
    after(:build) do |order, evaluator|
      create_list(:item, evaluator.items_count, order: order)
    end
  end
end
According to Factory Girl's Getting Started:
FactoryGirl.lint builds each factory and subsequently calls #valid? on it
However when I run my specs, Factory Girl throws an FactoryGirl::InvalidFactoryError because the order factory is invalid.
Workaround
after(:build) do |order, evaluator|
   evaluator.items_count.times do
     order.items << FactoryGirl.create(:item)
   end
   #create_list(:item, evaluator.items_count, order: order)
 end
According to the definition, it will call .valid? AFTER building. It seems that it will call this before running the after(:build) block.
Try writing you factory like this:
FactoryGirl.define do
  factory :order do
    ignore do
      items_count 1
    end
    items { build_list(:item, items_count) }
  end
end
This should build the item before the .valid? is called. 
Let me know if this works :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With