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
create_list(:item)
, do you haveitem
factory defined? – Neustriaafter(:create)
instead ofafter(:build)
for this because with just build theorder
is not saved and there is noorder_id
foritems
. – Neustriavalidates :items, presence: true
check ifitems.present?
returns true/false.order.items
returns[]
for new object.[].present?
returns true. So validation passes correctly – Countrywoman[].present?
does not return true. – Gravamenorder.items << FactoryGirl.create(:item, order: order)
, or are you relying on the item factory to create a different order? Does an item have one or many orders? – Gravamen[].present? # => true
I am wrong. I recheck Rails 4.1.1 works as expected and validation failed - record is invalid withoutitems
. Maybe Rails version is important for this stuff. – Countrywoman