Search code examples
ruby-on-railsfactory-bot

How can I reuse code for similar attributes with FactoryBot?


Say I've two models Person and Company, both are different models, however they both have one common attribute: address. If I were to use FactoryBot, I'd implement the respective factories as follows:

FactoryBot.define do
  factory :person do
    # ...
    address { Faker::Address.street_address }
  end
end

FactoryBot.define do
  factory :company do
    # ...
    address { Faker::Address.street_address }
  end
end

Is there a way where I can define an address generator that I can call from anywhere inside factories?. For example:

# define reusable attribute
FactoryBot.define do
    attribute :address { Faker::Address.street_address }
end

FactoryBot.define do
  factory :person do
    # ...
    generate_attribute(:address)
  end
end

FactoryBot.define do
  factory :company do
    # ...
    generate_attribute(:address)
  end
end

Currently I can replicate this desired behaviour with sequences, but it seems they're not meant for this task.


Solution

  • If you want to use a function anywhere inside factories, you can create a spec helper and define you function there:

    # AppSpecHelper
    # spec/support/app_spec_helper
    module AppSpecHelper
      def generate_attribute
        ...
      end
    end
    
    RSpec.configure do |c|
      c.include AppSpecHelper
    end
    

    In rails_helper.rb:

    RSpec.configure do |config|
      config.include AppSpecHelper
    end