Xiao Ning Wang
Xiao Ning Wang

Reputation: 38

NameError: uninitialized constant when referring to class within module

I have the following tests, written using RSpec

spec/services/aquatic/factory_spec.rb

describe Hobby::Aquatic::Factory do
  let(:factory) { Hobby::Aquatic::Factory.instance }

  describe "singleton" do

    it "should be the same object" do
      Hobby::Aquatic::Factory.instance.should be factory
    end

    it "raise error if given junk" do
      expect {factory.hobby("junk")}.to raise_error
    end
  end
end

spec/services/aquatic/hobbies_spec.rb

describe Hobby::Aquatic do
  it "creates fishing" do
    expect { Hobby::Aquatic::Fishing.new }.to_not raise_error
  end
end

and have defined the following module / classes

app/services/aquatic/factory.rb

require 'singleton'

module Hobby
  module Aquatic
    class Factory
      include Singleton

      def self.instance
        @@instance ||= new
      end

      def hobby(name)
        return Fishing.new if name == "fishing"
        return Surfing.new if name == "surfing"
        raise ArgumentError, "Unknown hobby for supplied name"
      end
    end
  end
end

app/services/aquatic/hobbies.rb

module Hobby
  module Aquatic
    class Fishing
    end

    class Surfing
    end
  end
end

When I run the tests the Factory tests all pass fine, but the test of the Hobby::Aquatic::Fishing object results in:

Failure/Error: expect { Hobby::Aquatic::Fishing.new }.to_not raise_error
   expected no Exception, got #<NameError: uninitialized constant Hobby::Aquatic::Fishing> …

What have I done wrong?

Upvotes: 1

Views: 1455

Answers (1)

Dave Sag
Dave Sag

Reputation: 13486

add require_relative 'hobbies' below require 'singleton' to fix this.

I am not sure why Rails is loading the factory but not the hobbies automagically but this works.

Upvotes: 1

Related Questions