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.
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
- Plain RSpec:
requirethe file inspec_helper.rbor userequire_relativein the spec. - Rails: rename the file/class so they match Zeitwerk’s expected constant exactly.
- Run
bin/rails zeitwerk:checkto surface naming mismatches before CI.
Add the gem to the test group
# Gemfile
group :development, :test do
gem 'factory_bot_rails'
endHow to prevent it
- Match filenames to class names so Zeitwerk autoloads cleanly.
- Run
zeitwerk:checkin CI to catch mismatches early. - Put test-only gems in the
:test(or:development, :test) group.