当类存在于子目录中并且是子类时,Rspec与load_missing_constant失败

时间:2012-08-14 18:09:05

标签: ruby-on-rails ruby-on-rails-3 rspec

由于我怀疑与自动加载相关的事情,我在运行一系列RSpec测试时遇到了一些麻烦。这是错误:

/usr/share/ruby-rvm/gems/ruby-1.9.2-p320/gems/activesupport-3.1.4/lib/active_support/dependencies.rb:490:in `load_missing_constant': Expected /var/lib/jenkins/.../portfolios/base_manage_controller.rb to define Portfolios::BaseManageController (LoadError)
from /usr/share/ruby-rvm/gems/ruby-1.9.2-p320/gems/activesupport-3.1.4/lib/active_support/dependencies.rb:181:in `block in const_missing'
from /usr/share/ruby-rvm/gems/ruby-1.9.2-p320/gems/activesupport-3.1.4/lib/active_support/dependencies.rb:179:in `each'
from /usr/share/ruby-rvm/gems/ruby-1.9.2-p320/gems/activesupport-3.1.4/lib/active_support/dependencies.rb:179:in `const_missing'
from /usr/share/ruby-rvm/gems/ruby-1.9.2-p320@global/gems/rake-0.9.2.2/lib/rake/ext/module.rb:36:in `const_missing'
from /var/lib/jenkins/jobs/.../app/controllers/portfolios/customize_controller.rb:1:in `<top (required)>'

这是文件的标题:

class Portfolios::BaseManageController < ApplicationController

它存在于app/controllers/portfolios/base_manage_controller.rb

及其子类:

class Portfolios::CustomizeController < Portfolios::BaseManageController

它存在于app/controllers/portfolios/customize_controller.rb

最后这里有一堆自动加载:

config.autoload_paths += Dir["#{config.root}/lib",  "#{config.root}/lib/**/"]
config.autoload_paths += %W(#{config.root}/app/models/statistics)

#Any test/dev specific load paths
if not Rails.env.production?
  config.autoload_paths += %W(#{config.root}/spec/support)
  config.autoload_paths += %W(#{config.root}/spec/support/builders)
  config.autoload_paths += %W(#{config.root}/spec/support/modules)
  config.autoload_paths += %W(#{config.root}/spec/support/utils)
end

非常感谢任何帮助!

4 个答案:

答案 0 :(得分:2)

当定义类时引发异常时,有时会发生此错误。在这种情况下,尝试定义base_manage_controller.rb中的类时可能会发生运行时错误。

要验证是这种情况,请尝试从base_manage_controller.rb中删除所有内容,但类声明除外:

class Portfolios::BaseManageController < ApplicationController
end

它应该导致规格运行,但失败。

要查找运行时错误,请将所有内容放回到类中,然后通过调用script/consolePortfolios::BaseManageController加载它。这将尝试动态加载类,并引发阻止您的类被定义的异常。

答案 1 :(得分:0)

Portfolios加载rspec时似乎未定义Portfolios::BaseManageController。您在哪里定义Portfolios?如果它被定义为单独文件中的模块或类,则需要首先require此文件。

答案 2 :(得分:0)

自动加载路径中存在冲突,因为/var/lib/jenkins/.../portfolios/base_manage_controller.rb中存在同名文件

您需要修改加载路径,以便app / controllers在列表的前面出现,或者重命名或删除上面路径中指定的文件。

答案 3 :(得分:0)

以下解决方案将帮助您

在app / controllers / portfolio / base_manage_controller.rb的以下路径中创建规范 的规格/控制器/组合/ base_manage_controller_spec.rb

规范内容应该是这样的

describe Portfolios::BaseManageController do
 -----
end

您可以为app / controllers / portfolio / customize_controller.rb

应用相同的逻辑