代码之家  ›  专栏  ›  技术社区  ›  btelles

rspec:用super(args)初始化控制器类时,rspec rails有问题吗?

  •  4
  • btelles  · 技术社区  · 15 年前

    我使用rspec已经有一段时间了,出于某种原因,我在一个名为referencesController的控制器上接收到错误。

    错误表明,我必须使用以下方法之一指定控制器名称:

     describe MyController do
    

     describe 'aoeuaoeu' do
       controller_name :my
    

    我试过两种变体:

     describe ReferencesController do
    

     describe 'refs controller' do
       controller_name :references
    

    但我两个都出错了!知道会发生什么事吗?

    伯尔尼

    编辑 :由于解决方案的性质,我修改了标题并添加了相关代码。这是错误的代码:

    #参考文件controller.rb

    class ReferencesController < ApplicationController
      def initialize(*args)  
        #do stuff
    
        super(args)   #  <= this is the problem line
      end
    
      def index
    
      end
    end
    

    错误:

        1)
        'ReferencesController GET index should take parameters for a company and return the references' FAILED
        Controller specs need to know what controller is being specified. You can
        indicate this by passing the controller to describe():
    
            describe MyController do
    
        or by declaring the controller's name
    
            describe "a MyController" do
                controller_name :my #invokes the MyController
        end
    
    2 回复  |  直到 15 年前
        1
  •  3
  •   John Hyland    15 年前

    如果你打电话 super(args) ,您正在传入一个参数-由引用的数组 args . 使用 "splat operator" - super(*args) -将数组转入列表并沿 阿尔茨海默病 作为一个单独的论点。

    正如韦恩所指出的,Ruby中还有一点语法上的糖分,你可以说 super 它会自动为你传递论点,把它当作 超级(*ARG) 而不仅仅是 super() .

    在你的特殊情况下,我猜你的控制器是超类的 initialize 方法不接受数组,所以当rspec试图实例化控制器时,它失败了,这最终导致了您看到的错误消息。

        2
  •  1
  •   btelles    15 年前

    呸!明白了…

    初始化方法有“super(args)”而不是“super(*args)”。

    如果有人想重写这个答案并给出一个完整的解释(或者解释为什么我不应该这样定义一个实例变量),我会很高兴地向上投票并给出被接受的答案。

    伯尼