Search code examples
ruby-on-railsfactory-bot

Add all Engine's factory paths dynamically


In support/factory_bot.rb we add all the Engine's factory paths like this:

require 'factory_bot'
FactoryBot.definition_file_paths.unshift(
  MyEngine::One.factory_path, 
  MyEngine::Two.factory_path,
  SomethingElse.factory_path, 
)
FactoryBot.find_definitions

if defined? RSpec
  RSpec.configure do |config|
    config.include FactoryBot::Syntax::Methods
  end
end

Is there a way to dynamically add all my Engine's factory paths in? For example, if we were to add a new engine, we wouldn't need to make any adjustments to this file.


Solution

  • I was able to dynamically add all the factory paths with the following:

    # frozen_string_literal: true
    require 'factory_bot'
    
    factory_paths = []
    
    Rails::Engine.subclasses.each do |klass|
      engine = klass.name.chomp('::Engine')
      if engine.constantize.methods.include?(:factory_path)
        factory_paths << engine.constantize.factory_path
      end
    end
    
    FactoryBot.definition_file_paths.unshift(*factory_paths)
    
    FactoryBot.find_definitions
    
    if defined? RSpec
      RSpec.configure do |config|
        config.include FactoryBot::Syntax::Methods
      end
    end