Solutions to the Annoying "Warning: Already Initialized Constant" Message

RSPec: Fix warning: already initialized constant for memoized class under test

  1. When you use Class.new you are creating an anonymous (unnamed) class.
  2. When constant is defined ruby needs to resolve the namespace for which the constant is defined.

Unlike in a module or a class the namespace within the anonymous class is empty.

class A
p Module.nesting # => [A]
B = 1
end
B #=> NameError: uninitialized constant B
A::B #=> 1

Class.new(A) do
p Module.nesting # => []
C = 1
end
C #=> 1

Since there is no explicit namespace where to put these constant, they end up getting defined "globally" in Object class.

You can try this yourself with following example (run it with --order defined):

require_relative 'spec_helper'

class Base
end

RSpec.describe Base do
context 'creating an anonymous class with a constant' do
let(:example_class) do
Class.new(described_class) do
DB_ID = 'example'

def foo
'foo'
end
end
end

it 'does foo' do
expect(example_class.new.foo).to eq('foo')
end
end

context 'the constant is on Object' do
it 'does bar' do
expect(DB_ID).to eq('example')
end
end
end

It boils down to how ruby constant lookup works. Here is a nice post about it https://cirw.in/blog/constant-lookup.html.

warning: already initialized constant Mime::PDF

Not sure, Try to add below code into config/initializers/mime_types.rb file.

Mime::Type.register 'application/pdf', :pdf

It looks like newer versions of rails already registers it.

OR

Try using lookup_by_extenstion before defining it.

In same config/initializers/mime_types.rb file.

Mime::Type.register "application/pdf", :pdf unless Mime::Type.lookup_by_extension(:pdf)


Related Topics



Leave a reply



Submit