factory_bot Email Factory

in code


While hardly a world-shattering bit of code, I’ve found this super useful for reuse. :D

FactoryBot.define do
  factory :email_address, class: String do
    skip_create

    transient do
      sequence(:address) { |n| "factory_email_#{n}@example.com" }
    end

    initialize_with do
      new address if address
    end
  end
end

Call inside a factory thus:

FactoryBot.define do
  factory :foobar do
    email { create :email_address }
  end
end

To explain the calling above, factory_bot doesn’t build associations when you call attributes_for. If :foo above only had email as an attribute, then attributes_for :foo would return {}. To step around this I create an email_address and assign it to email.

Anyhow.




Your email address will not be published. Required fields are marked *