NameError:引用模块中的类时未初始化的常量

时间:2014-09-18 02:12:57

标签: ruby rspec module

我有以下测试,使用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

并定义了以下模块/类

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

当我运行测试时,Factory测试所有传递正常,但Hobby::Aquatic::Fishing对象的测试导致:

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

我做错了什么?

1 个答案:

答案 0 :(得分:1)

require_relative 'hobbies'下方添加require 'singleton'以解决此问题。

我不确定为什么Rails会自动加载factory而不加载hobbies,但这样做有效。