Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

728
Views
Rspec uninitialized constant for class nested inside module - Ruby on Rails

In a Rails project, I have created a new class inside the lib directory, this class is namespaced inside a module. When creating a spec file for it, I'm seeing NameError: uninitialized constant MyNamespace.

Here is my folder structure

app/
...
lib
  my_namespace
    my_new_class.rb
  another_namespace
    another_old_class.rb
spec
  lib
    my_namespace
      my_new_class_spec.rb
    another_namespace
      another_old_class_spec.rb

Here the (abbreviated) contents of: lib/my_namespace/my_new_class.rb

module MyNamespace
  class MyNewClass
  end
end

spec/lib/my_namespace/my_new_class_spec.rb

RSpec.describe MyNamespace::MyNewClass do
  it "is true"
    expect(true).to eq(true) # irrelevant at this point
  end
end

The reason I included another_old_class_spec.rb is that its tests run without issue and I can't find anywhere that it's explicitly loaded or required in the test setup (in case that might be a potential issue).

When running the test with bundle exec rspec spec/lib/my_namespace/my_new_class_spec.rb or even bundle exec rspec spec/lib/my_namespace/ I get

An error occurred while loading ./spec/lib/my_namespace/my_new_class_spec.rb
Failure/Error:
RSpec.describe MyNamespace::MyNewClass do

NameError:
  uninitialized constant MyNamespace
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Like Georgiy Melnikov implied in his comment, by default the /lib directory is not in autoload paths, so the constant MyNamespace is not automatically resolved.

You basically have two options to fix this:

  1. explicitly require the file with require lib/my_namespace/my_new_class at the top of the spec file
  2. add lib/ to autoload paths (nowadays this is discouraged)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!