Back to Repositories

Testing Class-Based Factory Resolution in factory_bot

This test suite examines FactoryBot’s behavior when attempting to create factory instances using class names instead of symbols. It specifically validates the error handling when factories are referenced by their actual class rather than the conventional symbol notation.

Test Coverage Overview

The test coverage focuses on FactoryBot’s factory lookup mechanism and error handling.

  • Tests factory creation using class reference instead of symbols
  • Verifies error handling for unregistered factory lookups
  • Validates KeyError exception messages

Implementation Analysis

The testing approach uses RSpec’s expect syntax to verify FactoryBot’s error handling behavior. It employs define_model helper to create a test User model and establishes a minimal factory definition.

  • Uses RSpec’s raise_error matcher
  • Implements before block for test setup
  • Utilizes FactoryBot’s define method

Technical Details

  • RSpec testing framework
  • FactoryBot factory definition
  • Dynamic model definition
  • Error expectation testing
  • Class-based factory reference testing

Best Practices Demonstrated

The test demonstrates clean testing practices by isolating the specific behavior being tested and using clear, descriptive error expectations. It follows FactoryBot’s conventional testing patterns and properly sets up test prerequisites.

  • Isolated test scenario
  • Clear error expectations
  • Proper test setup
  • Focused test scope

thoughtbot/factory_bot

spec/acceptance/keyed_by_class_spec.rb

            
describe "finding factories keyed by class instead of symbol" do
  before do
    define_model("User") do
      attr_accessor :name, :email
    end

    FactoryBot.define do
      factory :user
    end
  end

  it "doesn't find the factory" do
    expect { FactoryBot.create(User) }.to(
      raise_error(KeyError, /Factory not registered: User/)
    )
  end
end