1. What is FactoryBot?

    FactoryBot is a Ruby library for setting up test data efficiently. Instead of manually creating test records in each test case, FactoryBot provides a factory-based approach to generate test data dynamically.

  2. Why Use FactoryBot?

  3. Installation & Setup

  4. Factory Directory & File Structure

    FactoryBot stores factory definitions in the spec/factories directory.

  5. Example: Expense Factory

    A factory for the Expense model has already been created:

    FactoryBot.define do
      factory :expense do
        name { "Internet Bill" }
        amount { 69.00 }
        date { Date.new(2025, 1, 31) }
        category { "Utilities" }
      end
    end
    

    This allows for easy test data creation:

    let(:expense) { create(:expense) } # Creates a valid Expense object
    
  6. How to Use FactoryBot in Tests

    expense = create(:expense)
    
    expenses = create_list(:expense, 5)
    
  7. Troubleshooting Common Issues