'Remove associations when using a Factory with associations

I have a simple :item factory with a nested attachment that is working fine.

FactoryGirl.define do
  factory :item do
    before_create do |item|
      item.attachments << FactoryGirl.build(:attachment, attachable: item)
    end
  end
end

I want to check for the following

it "is invalid without a photo" do 
  FactoryGirl.create(:item).should_not be_valid
end

How can I delete the attachments when calling the existing :item factory?



Solution 1:[1]

You may want to have two versions of the item factory. One that does not create the associated attachments, and one that does. This will let you have an item factory for other places without the dependency on attachments.

FactoryGirl.define do
  factory :item
end

FactoryGirl.define do
  factory :item_with_attachments, :parent => :item do
    before_create do |item|
      item.attachments << FactoryGirl.build(:attachment, attachable: item)
    end
  end
end

Another option would be to just remove the attachments before testing its validity:

it "is invalid without a photo" do 
  item = FactoryGirl.create(:item)
  item.attachments.destroy_all
  item.should_not be_valid
end

Solution 2:[2]

Use traits:

FactoryGirl.define do
  factory :item do
    # default vals
  end

  trait :with_attachments do
    attachments { |item| FactoryGirl.build_list(:attachment, 1, attachable: item) }
  end
end

usage

FactoryGirl.create(:item, :with_attachments)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fkoessler
Solution 2 Damien Roche