Factory Bot uniq slug

November 21, 2020

How to use Factory Bot to have a uniq slug and create as much as you want.

Factory

FactoryBot.define do
  factory :example do
    slug 'example1'

    initialize_with { Example.find_or_initialize_by(slug: slug) }
  end
end

Example Used:

create(:example, slug: 'ex').id == create(:example, slug: 'ex').id

Search