【问题标题】:Controller test: RuntimeError: @controller is nil. How to refer to controller if the controller is in a subfolder?控制器测试:RuntimeError:@controller 为零。如果控制器在子文件夹中,如何引用控制器?
【发布时间】:2016-01-18 14:08:48
【问题描述】:

我有以下控制器:

  • /controllers/api/base_controller.rb
  • /controllers/api/v1/articles_controller.rb

在为文章运行控制器测试时,我收到错误 RuntimeError: @controller is nil: make sure you set it in your test's setup method。我的测试文件以:

开头
require 'test_helper'
class ApiArticlesControllerTest < ActionController::TestCase
  etc...

class 行应该是什么?我尝试了几个版本,但都没有成功。

【问题讨论】:

  • /controllers/api/v1/articles_controller.rb 中的类的名称是什么?
  • 该控制器的第一行是:module Apimodule V1 ; class ArticlesController &lt; Api::BaseController
  • 所以你应该将你的控制器称为Api::V1::ArticlesController

标签: ruby-on-rails ruby-on-rails-4 testing


【解决方案1】:

您的控制器名称是有范围的,因此您应该将其称为Api::V1::ArticlesController

Scoped 表示它的名称在另一个模块的范围内(“下”),在您的情况下,其中有两个 ApiV1

将您的测试更改为class Api::V1::ArticlesControllerTest &lt; ActionController::TestCase 应该可以解决您的问题。

编辑

如果上述方法不起作用,您还可以执行以下操作

class ApiArticlesControllerTest < ActionController::TestCase
  tests Api::V1::ArticlesController

【讨论】:

    猜你喜欢
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    相关资源
    最近更新 更多