Back to Repositories

Testing Callback Parameter Handling in factory_bot

This test suite examines the callback functionality in FactoryBot, focusing on callback name handling and parameter passing. The tests verify callback initialization, name normalization, and execution with different parameter configurations.

Test Coverage Overview

The test suite provides comprehensive coverage of FactoryBot’s Callback class functionality.

  • Callback name assignment and symbol conversion
  • Parameter handling with zero, one, and two arguments
  • Block execution verification
  • String to symbol conversion for callback names

Implementation Analysis

The testing approach uses RSpec’s describe/it blocks to systematically verify callback behavior.

Tests employ lambda functions to validate parameter passing and execution contexts, with explicit verification of return values and parameter handling. The implementation leverages RSpec’s expectation syntax for clear assertion definition.

Technical Details

  • Testing Framework: RSpec
  • Test Subject: FactoryBot::Callback class
  • Testing Patterns: Lambda functions, expectation matching
  • Assertion Methods: eq matcher

Best Practices Demonstrated

The test suite exemplifies strong testing practices through focused, isolated test cases.

  • Single responsibility principle in test cases
  • Clear test descriptions
  • Consistent assertion patterns
  • Progressive complexity in test scenarios

thoughtbot/factory_bot

spec/factory_bot/callback_spec.rb

            
describe FactoryBot::Callback do
  it "has a name" do
    expect(FactoryBot::Callback.new(:after_create, -> {}).name).to eq :after_create
  end

  it "converts strings to symbols" do
    expect(FactoryBot::Callback.new("after_create", -> {}).name).to eq :after_create
  end

  it "runs its block with no parameters" do
    ran_with = nil
    FactoryBot::Callback.new(:after_create, -> { ran_with = [] }).run(:one, :two)
    expect(ran_with).to eq []
  end

  it "runs its block with one parameter" do
    ran_with = nil
    FactoryBot::Callback.new(:after_create, ->(one) { ran_with = [one] }).run(:one, :two)
    expect(ran_with).to eq [:one]
  end

  it "runs its block with two parameters" do
    ran_with = nil
    FactoryBot::Callback.new(:after_create, ->(one, two) { ran_with = [one, two] }).run(:one, :two)
    expect(ran_with).to eq [:one, :two]
  end
end