Class: Philiprehberger::TestFactory::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/test_factory/builder.rb

Overview

Builds data hashes from factory definitions.

Instance Method Summary collapse

Constructor Details

#initialize(registry) ⇒ Builder

Create a new builder.

Parameters:

  • registry (Registry)

    the registry to look up definitions



10
11
12
# File 'lib/philiprehberger/test_factory/builder.rb', line 10

def initialize(registry)
  @registry = registry
end

Instance Method Details

#attributes_for(name, traits: [], **overrides) ⇒ Hash

Build the attribute hash without firing after_build callbacks or resolving associations. Mirrors FactoryBot’s ‘attributes_for`.

Parameters:

  • name (Symbol)

    factory name

  • traits (Array<Symbol>) (defaults to: [])

    trait names to apply

  • overrides (Hash)

    explicit attribute overrides

Returns:

  • (Hash)

    the resolved attribute hash

Raises:

  • (Error)

    if the factory is not defined



38
39
40
41
# File 'lib/philiprehberger/test_factory/builder.rb', line 38

def attributes_for(name, traits: [], **overrides)
  result, = resolve_attributes(name, traits: traits, resolve_associations: false, **overrides)
  result
end

#build(name, traits: [], **overrides) ⇒ Hash

Build a single data hash from a factory definition.

Parameters:

  • name (Symbol)

    factory name

  • traits (Array<Symbol>) (defaults to: [])

    trait names to apply

  • overrides (Hash)

    explicit attribute overrides

Returns:

  • (Hash)

    the built data hash

Raises:

  • (Error)

    if the factory is not defined



21
22
23
24
25
26
27
28
# File 'lib/philiprehberger/test_factory/builder.rb', line 21

def build(name, traits: [], **overrides)
  result, transient_values, proxy = resolve_attributes(name, traits: traits, resolve_associations: true, **overrides)

  # Run after_build callbacks with the result and transient context
  proxy.after_build_callbacks.each { |cb| cb.call(result, transient_values) }

  result
end

#build_list(name, count, traits: [], **overrides) ⇒ Array<Hash>

Build a list of data hashes.

Each element goes through the normal build path so sequences, associations, and callbacks run once per object. Overrides and traits apply identically to every element in the list.

Parameters:

  • name (Symbol)

    factory name

  • count (Integer)

    number of items to build (must be >= 0)

  • traits (Array<Symbol>) (defaults to: [])

    trait names to apply

  • overrides (Hash)

    explicit attribute overrides

Returns:

  • (Array<Hash>)

    the built data hashes

Raises:

  • (ArgumentError)

    if count is negative



55
56
57
58
59
# File 'lib/philiprehberger/test_factory/builder.rb', line 55

def build_list(name, count, traits: [], **overrides)
  raise ArgumentError, "count must be non-negative, got #{count}" if count.negative?

  Array.new(count) { build(name, traits: traits, **overrides) }
end