【问题标题】:Rails 4.0 RuntimeError: @controller is nil: make sure you set it in your test's setup methodRails 4.0 RuntimeError: @controller is nil: 确保在测试的 setup 方法中设置它
【发布时间】:2014-12-01 19:41:42
【问题描述】:

当我运行控制器(或功能)测试时,Rails 4.0 无法自动实例化控制器实例 (@controller),即使相同的测试在 Rails 3.2 中运行良好。
有关如何开始解决此问题的任何建议?

样本输出:

 $ ruby -Ilib:test test/controllers/account_controller_test.rb
[Coveralls] Set up the SimpleCov formatter.
[Coveralls] Using SimpleCov's 'rails' settings.
warning: parser/current is loading parser/ruby21, which recognizes
warning: 2.1.5-compliant syntax, but you are running 2.1.3.

...

  1) Error:
AccountControllerTest#test_activate_api_key:
NoMethodError: undefined method `before_filter' for AccountController:Class
    app/controllers/account_controller.rb:47:in `<class:AccountController>'
    app/controllers/account_controller.rb:46:in `<top (required)>'

  2) Error:
AccountControllerTest#test_add_mugshot:
RuntimeError: @controller is nil: make sure you set it in your test's setup method.
    test/functional_test_case.rb:26:in `post'
    test/controller_extensions.rb:533:in `assert_request'
    test/controller_extensions.rb:202:in `either_requires_either'
    test/controller_extensions.rb:137:in `post_requires_login'
    test/controllers/account_controller_test.rb:418:in `test_add_mugshot'

帐户控制器定义:

class AccountController < ApplicationController
  before_filter :login_required, :except => [

应用控制器:

class ApplicationController < ActionController::Base

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-4 minitest testunit


【解决方案1】:

AccountController的定义过程中使用ApplicationController似乎不是从ActionController::Base派生的,所以在AccountController声明之前添加require

# file app/controllers/account_controller.rb
require 'app/controllers/application_controller'

class AccountController < ApplicationController
  before_filter :login_required, :except => [

【讨论】:

  • 谢谢Малъ Скрылевъ!添加一个需求解决了这个问题。问题似乎来自 Rails 4 中以不同顺序加载的文件。应用程序的 test_helper 文件试图重新打开 ApplicationController 的定义。这在 Rails 3 中运行良好。但看起来 Rails 4 在加载控制器之前加载了 test_helper。因此,test_helper 文件没有重新打开 ApplicationController,而是给了它一个初始定义,该定义不是从 ActionController::Base 派生的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-02
  • 1970-01-01
相关资源
最近更新 更多