Today I Learned

Handling uniqueness violations in factories

If it happens that your factories’ cross-dependencies result in creating records that violate uniqueness constraint, you can can fix it quick’n’dirty way

FactoryGirl.define do
  factory :day do
    initialize_with {
      Day.where(date: date).first_or_initialize
    }

    sequence(:date) { |n| Date.current + n.days }
  end
end

Ba aware that this is just a hack, and a hack that would add 1 SQL query to each creation of given object. Preferred way is to fix underlying problem. Still, if you do not care about retrieving the actual instance of object from factory, then different strategy can be used, that would mitigate extra query problem.

FactoryGirl.define do
  factory :day do
    to_create do |day|
      day.save!
    rescue ActiveRecord::RecordNotUnique
      Day.find_by(date: day.date)
    end

    sequence(:date) { |n| Date.current + n.days }
  end
end

If for any reason you really need to handle this kind of case, then introducing a custom create strategy (i.e. find_or_create(:day)) might be a way to go.