Home > database >  uninitialised constant after upgrade of Gemfile
uninitialised constant after upgrade of Gemfile

Time:03-03

I've just updated my Gemfile.

At the beginning I thought problem came from Zeitwerk (from 2.4.2 to 2.5.4) but I've downgraded it and I still have an issue on my spec. I've isolated that the problem does not come from RSpec and dependencies.

Actually, RSpec does not found a class which is defined within another file and does not match the file name/class name.

Important point: Filter::MyStandardError is found.

# app/services/filter/my_standard_error.rb
module Filter
  class MyStandardError < StandardError; end

  class MySpecificError < MyStandardError; end
  # ...
end
# app/services/filter/my_tested_service.rb
module Filter
  class MyTestedService

    def initialize
      raise ::Filter::MySpecificError
    end
  end
end
RSpec.describe Filter::MyTestedService do
  subject { described_class.new }

  it 'raises an error'
    expect{subject}.to raise_error(::Filter::MySpecificError)
  end
end

And I got the error:

NameError:
       uninitialized constant Filter::MySpecificError

I got the Changelog but breaking changes are not used on my configuration.

Does anybody have an idea for this one?

CodePudding user response:

You edited the description.

Are those real filenames, real contents, and real class/module names? Or are they fake?

CodePudding user response:

You do not need to add app/services to the autoload paths, that is done automatically by Rails. I'd suggest to remove that configuration to keep things simple/idiomatic.

The implementation of app/services/filter.rb should not be needed. Your application is doing something that is not right, we just need to find it.

Could you please delete app/services/filter.rb, throw Rails.autoloaders.log! in config/application.rb, trigger the error, and share the traces?

CodePudding user response:

Oh, the description is edited again!

You cannot define two constants at the same level in the same file. It is one constant, one file. This has not changed in Zeitwerk upgrades. You need one file for the standard error, and another file for the specific error.

CodePudding user response:

After reading one-file-one-constant-at-the-same-top-level

I found this to fix my issue

# app/services/filter.rb
class Filter
  class MyStandardError < StandardError; end

  class MySpecificError < MyStandardError; end
end
# app/services/filter/my_tested_service.rb
class Filter
  class MyTestedService

    def initialize
      raise ::Filter::MySpecificError
    end
  end
end

I still don't know why it was working before..

  • Related