Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating That A has_many Association Has At Least One Model When Using FactoryGirl

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
like image 802
Undistraction Avatar asked Jun 20 '14 14:06

Undistraction


1 Answers

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 :)

like image 167
amerdidit Avatar answered Sep 23 '22 16:09

amerdidit