ruby-on-railsrubyrspec

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

Solution

  • 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)