RSPec: Fix warning: already initialized constant for memoized class under test
- When you use
Class.new
you are creating an anonymous (unnamed) class. - 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
Rails Model Name Conflict with Included Gem
Troubleshooting Ssl Certificates, Ruby, MAC Os X Yosemite
Ruby Method Calls Declared in Class Body
How to Remove Carriage Returns with Ruby
Check If a Hash's Keys Include All of a Set of Keys
Creating Signature and Nonce for Oauth (Ruby)
Getting Ruby 1.8.7 Installed on Mountain Lion (10.8)
How to Pass a Custom Comparator to "Sort"
How to Emit Comments in a Yaml Document Using Psych
How to Use Same Terminal Window After Using "Rails Server" Command
How to Programmatically Generate Heroku-Like Subdomain Names
Ruby - Can't Modify Frozen String (Typeerror)
Ruby/Rails CSV Parsing, Invalid Byte Sequence in Utf-8
Nicely Formatting Output to Console, Specifying Number of Tabs
What's the Best Way to Deploy a Jruby on Rails Application to Tomcat