Skip to content

Add factory_bot.before_run_factory instrumentation event#1795

Open
hammadxcm wants to merge 1 commit intothoughtbot:mainfrom
hammadxcm:add-before-run-factory-instrumentation
Open

Add factory_bot.before_run_factory instrumentation event#1795
hammadxcm wants to merge 1 commit intothoughtbot:mainfrom
hammadxcm:add-before-run-factory-instrumentation

Conversation

@hammadxcm
Copy link
Contributor

Summary

  • Adds a new factory_bot.before_run_factory ActiveSupport::Notifications event that fires immediately before run_factory
  • Enables subscribers to build a factory call stack at runtime for debugging deeply nested association errors
  • Reuses the existing instrumentation_payload — no new payload construction needed

Closes #1673

Motivation

When factories are deeply nested via associations, errors in after callbacks only surface the top-level factory in the stack trace. A before_run_factory event lets users push/pop a call stack to identify the exact factory chain that led to an error.

Existing alternatives don't work:

  • Global callbacks can't access the factory name
  • compile_factory only fires once per factory definition (cached)
  • Custom start/finish subscriber on run_factory works but is an obscure pattern most users won't discover

Changes

File Change
lib/factory_bot/factory_runner.rb Added one-line non-block instrument call before existing run_factory block
spec/acceptance/activesupport_instrumentation_spec.rb Added 3 tests: payload correctness, firing order, nested call stack capture
docs/src/activesupport-instrumentation/summary.md Documented new event with call-stack example
GETTING_STARTED.md Mirrored documentation update
NEWS.md Added changelog entry

Test plan

  • All 3 new tests pass (bundle exec rspec spec/acceptance/activesupport_instrumentation_spec.rb)
  • Full test suite passes (763 examples, 0 failures)
  • bundle exec rake standard — no formatting offenses

Fire a non-block ActiveSupport::Notifications event immediately before
the existing `run_factory` instrument block. This allows subscribers to
build a factory call stack at runtime, which is useful for debugging
errors in deeply nested association callbacks where the standard stack
trace only shows the top-level factory.

The payload is identical to `run_factory` (`:name`, `:strategy`,
`:traits`, `:overrides`, `:factory`).

Closes thoughtbot#1673
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add factory_bot.before_factory_run instrumentation event

1 participant