factory_bot_rails

repository·main·Indexed 25 days ago

https://github.com/thoughtbot/factory_bot_rails

Provides seamless Rails integration for factory_bot, a fixtures replacement tool. It includes automatic factory definition loading, support for file fixtures via ActiveSupport::Testing::FileFixtures, and a custom Rails generator (factory_bot:model) to create factory files for models.

Tokens
989
Snippets
4
Records
8
Agent score
75%

What's inside factory_bot_rails

  1. Configure Rails generators for factory_bot

    main

    When factory_bot_rails is in your :development group, Rails will generate factories instead of fixtures. You can customize this behavior using the config.generators block.

    # Disable factory generation via generators
    config.generators do |g|
      g.factory_bot false
    end
    
    # Specify a custom directory for generated factories
    config.generators do |g|
      g.factory_bot dir: 'custom/dir/for/factories'
    end
    
    # Add a suffix to generated filenames (e.g., users_factory.rb)
    config.generators do |g|
      g.factory_bot suffix: "factory"
    end
    
    # Use a proc to customize filenames
    config.generators do |g|
      g.factory_bot filename_proc: ->(table_name) { "prefix_#{table_name}_suffix" }
    end
  2. Configure automatic factory definition loading

    main

    By default, factory_bot_rails automatically loads factories from factories.rb, test/factories.rb, spec/factories.rb, and any .rb files in factories/, test/factories/, or spec/factories/ relative to the Rails root.

    You can customize these paths using config.factory_bot.definition_file_paths. To disable automatic loading entirely, set this to an empty array.

  3. Configure factory_bot_rails settings

    main

    You can configure factory_bot_rails via the Rails configuration object using config.factory_bot.

    Available configuration keys:

    • definition_file_paths: An array of paths (relative to Rails.root) where your factory definitions are located. By default, this uses FactoryBot.definition_file_paths.
    • validator: An instance of FactoryBotRails::FactoryValidator used for validating factories.
    • file_fixture_support: A boolean that enables or disables support for file fixtures. Defaults to true.
  4. Generate a factory for a model

    main

    Use the factory_bot:model generator to create a factory file for a specific Rails model. You can pass attributes directly to the command to pre-populate the factory definition.

    Arguments

    • attributes: An array of field:type pairs (e.g., name:string email:string) to define the factory's attributes.

    Options

    • --dir: The directory or file root where the factory file should be placed. Defaults to test/factories.
    • --suffix: A suffix to add to the generated factory filename.

    If the target file already exists, the generator will attempt to insert the new factory definition into the existing file after the FactoryBot.define do block.