Skip to content
Latchkey

RSpec "NameError: uninitialized constant" - Fix Autoload in CI

Ruby could not resolve a constant a spec references. Either the file defining it was never required, the filename does not match the class name for the autoloader, or the gem is missing from the test group.

What this error means

A spec fails to load with "NameError: uninitialized constant SomeClass." In a Rails app it may be a Zeitwerk message about a file not defining the expected constant. The class works in some contexts but not where the spec loads it.

RSpec output
NameError:
  uninitialized constant PaymentProcessor

  ./spec/services/payment_processor_spec.rb:4:in `<top (required)>'

Common causes

File not required (non-Rails / plain RSpec)

Without Rails autoloading, the file defining the constant must be required (often via spec_helper). If it is not, the constant is undefined when the spec loads.

Zeitwerk filename/class mismatch

Rails’ Zeitwerk loader expects app/services/payment_processor.rb to define PaymentProcessor. A name mismatch (or wrong nesting) raises "expected file to define constant".

Gem missing from the test group

A constant from a gem only listed under group :development (not :test) is undefined when specs run in the test environment.

How to fix it

Require the file or fix Zeitwerk naming

  1. Plain RSpec: require the file in spec_helper.rb or use require_relative in the spec.
  2. Rails: rename the file/class so they match Zeitwerk’s expected constant exactly.
  3. Run bin/rails zeitwerk:check to surface naming mismatches before CI.

Add the gem to the test group

Gemfile
# Gemfile
group :development, :test do
  gem 'factory_bot_rails'
end

How to prevent it

  • Match filenames to class names so Zeitwerk autoloads cleanly.
  • Run zeitwerk:check in CI to catch mismatches early.
  • Put test-only gems in the :test (or :development, :test) group.

Frequently asked questions

What causes ""uninitialized constant""?
Without Rails autoloading, the file defining the constant must be required (often via spec_helper). If it is not, the constant is undefined when the spec loads.
How do I fix "uninitialized constant"?
Require the file or fix Zeitwerk naming

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card