使用rspec而不是Rails的“无法自动加载常量”

Lin*_*der 5 rspec ruby-on-rails

我有这个文件要测试。

app/workers/station/http.rb

module Worker
  module Station
    class HTTP
      # ...
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

这是我的规格文件。

spec/workers/station/http_spec.rb

describe Worker::Station::HTTP do
  it "should do something"  do
  end 
end
Run Code Online (Sandbox Code Playgroud)

现在的问题是,使用rspec运行spec文件时出现以下错误。

rspec spec/workers/station/http_spec.rb

/Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/activesupport-4.0.4/lib/active_support/dependencies.rb:464:in `load_missing_constant': Unable to autoload constant Station::HTTP, expected app/workers/station/http.rb to define it (LoadError)
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/activesupport-4.0.4/lib/active_support/dependencies.rb:184:in `const_missing'
  from spec/workers/station/http_spec.rb:3:in `<top (required)>'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/activesupport-4.0.4/lib/active_support/dependencies.rb:223:in `load'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/activesupport-4.0.4/lib/active_support/dependencies.rb:223:in `block in load'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/activesupport-4.0.4/lib/active_support/dependencies.rb:214:in `load_dependency'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/activesupport-4.0.4/lib/active_support/dependencies.rb:223:in `load'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/rspec-core-2.14.8/lib/rspec/core/configuration.rb:896:in `block in load_spec_files'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/rspec-core-2.14.8/lib/rspec/core/configuration.rb:896:in `each'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/rspec-core-2.14.8/lib/rspec/core/configuration.rb:896:in `load_spec_files'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/rspec-core-2.14.8/lib/rspec/core/command_line.rb:22:in `run'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/rspec-core-2.14.8/lib/rspec/core/runner.rb:80:in `run'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/rspec-core-2.14.8/lib/rspec/core/runner.rb:17:in `block in autorun'
  from /Users/linus/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
  from /Users/linus/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
Run Code Online (Sandbox Code Playgroud)

奇怪的是,一切都可以在控制台中工作。

$ rails c [1] pry(main)> Worker::Station::HTTP => Worker::Station::HTTP

为什么使用rspec而不是在Rails中发生这种情况,我将如何解决?

我正在使用

  • 导轨(4.0.4)
  • rspec(2.14.1)

jfo*_*off 1

app/workers路径不会被 rspec 自动加载,因为它不是标准的 Rails 布局,您可以将自动加载行添加到您的 spec_helper 或直接在规范中需要文件!