Rails和rspec。未初始化的常量错误

时间:2015-10-31 14:27:38

标签: ruby-on-rails testing rspec

我有一个rails App。我有这个文件app / errors / status.rb

我尝试通过测试但是没有工作。

module Errors 
  class Status
    def initialize status
      @status = status
    end

    def default_message
      "Error in the server status: #{status}"
    end

    private

    attr_reader :status
  end
end

对spec / errors / status_spec.rb的测试:

require 'rails_helper'

describe Errors::Status do
  let(:status) { double 'status' }

  subject { described_class.new status }

  describe 'default_message' do
    it 'returns the default message' do
      expect(subject.call).to eq( "Error in the server status: #{status}")
    end
  end
end

它一直在抛出这个错误:

/Users/gerardmorera/bet_play/spec/errors/status_spec.rb:3:in `<top (required)>': uninitialized constant Errors (NameError)
    from /Users/gerardmorera/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1327:in `load'
    from /Users/gerardmorera/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1327:in `block in load_spec_files'
    from /Users/gerardmorera/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1325:in `each'
    from /Users/gerardmorera/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1325:in `load_spec_files'
    from /Users/gerardmorera/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/rspec-core-3.3.2/lib/rspec/core/runner.rb:102:in `setup'
    from /Users/gerardmorera/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/rspec-core-3.3.2/lib/rspec/core/runner.rb:88:in `run'

1 个答案:

答案 0 :(得分:1)

这是因为ActiveSupport的自动加载工作方式以及Rails设置$LOAD_PATH的方式。 Autoload会看到Errors::Status并希望通过errors/statusrequire找到它,但不是因为app/errors位于$LOAD_PATH,所以您需要您的文件只有require 'errors'

您可以通过将app/errors/status.rb移至ActiveSupport的自动加载预期位置(例如app/<something>/errors/status.rb)来解决此问题。您可以puts $LOAD_ATH查看所有可能的位置(请注意,Rails会将app/中的所有目录添加到$LOAD_PATH)。