Back to Repositories

Testing AttributeHash Decorator Implementation in factory_bot

This test suite examines the AttributeHash decorator in FactoryBot, focusing on attribute handling and hash generation functionality. The tests verify proper attribute extraction and handling of edge cases, particularly when dealing with nested attribute structures.

Test Coverage Overview

The test suite provides comprehensive coverage of the AttributeHash decorator’s core functionality, specifically focusing on attribute hash generation and handling.

  • Tests basic attribute hash generation with multiple attributes
  • Verifies handling of special case with ‘attributes’ as a key
  • Ensures proper component interaction and attribute extraction

Implementation Analysis

The testing approach utilizes RSpec’s double mocking system to isolate the decorator’s behavior from its dependencies. The implementation employs a clean, focused testing pattern that verifies both standard operations and edge cases.

  • Uses RSpec doubles for component isolation
  • Implements context-based test organization
  • Validates decorator interface consistency

Technical Details

  • RSpec testing framework
  • FactoryBot decorator pattern implementation
  • Test doubles for dependency isolation
  • Attribute hash manipulation and verification

Best Practices Demonstrated

The test suite exemplifies several testing best practices, including proper isolation of components and clear test organization. It demonstrates effective use of RSpec’s context blocks and expectation syntax while maintaining focused test cases.

  • Clean test isolation using doubles
  • Clear context separation
  • Focused test cases with single responsibilities
  • Proper edge case coverage

thoughtbot/factory_bot

spec/factory_bot/decorator/attribute_hash_spec.rb

            
describe FactoryBot::Decorator::AttributeHash do
  describe "#attributes" do
    it "returns a hash of attributes" do
      attributes = {attribute_1: :value, attribute_2: :value}
      component = double(:component, attributes)

      decorator = described_class.new(component, [:attribute_1, :attribute_2])

      expect(decorator.attributes).to eq(attributes)
    end

    context "with an attribute called 'attributes'" do
      it "does not call itself recursively" do
        attributes = {attributes: :value}
        component = double(:component, attributes)

        decorator = described_class.new(component, [:attributes])

        expect(decorator.attributes).to eq(attributes)
      end
    end
  end
end