我有一个Rails应用程序。我有这个文件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'
最佳答案
这是因为ActiveSupport的自动加载方式以及Rails设置$LOAD_PATH
的方式。自动加载会看到Errors::Status
并希望通过errors/status
在require
的某个位置找到它,但这不是因为app/errors
位于$LOAD_PATH
中,因此您只需要文件require 'errors'
。
您可以通过将app/errors/status.rb
移至ActiveSupport预期自动加载的位置(例如app/<something>/errors/status.rb
)来解决此问题。您可以puts $LOAD_ATH
查看所有可能的位置(请注意,Rails会将app/
中的所有目录添加到$LOAD_PATH
中)。
关于ruby-on-rails - Rails和rspec。未初始化的常量错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33452678/