【问题标题】:Stub ApplicationController Class Method With Rspec带有 Rspec 的 Stub ApplicationController 类方法
【发布时间】:2012-10-28 00:54:00
【问题描述】:

如何在 Rspec 中存根 set_headers 类方法?

application_controller.rb

class ApplicationController < ActionController::Base

  def self.set_headers(name) 
     after_filter do
       object = instance_variable_get("@#{name}")
       headers['fancy'] = object.fancy_header
     end
  end

end

regular_controller.rb

class RegularController < ApplicationController
  set_headers :regular

  def index
    # do regular stuff
  end
end    

我尝试了以下方法,但它不起作用。

regular_controller_spec.rb

describe RegularController do
  before(:each) do
    ApplicationController.any_instance.stub(:set_headers).and_return({this: 'params'})
  end
end

【问题讨论】:

    标签: ruby-on-rails rspec tdd


    【解决方案1】:

    刚刚快速测试了一下,发现应该可以:

    controller.class.stub(:set_headers).and_return({this: 'params'})  
    

    【讨论】:

      【解决方案2】:

      这里有多个问题:

      • set_headers 在定义 RegularController 时被调用。这在规范运行之前很久就发生了,因此存根 set_headers 方法不会有任何影响。
      • 在您的RegularController 类定义中,set_headers 的接收者是RegularController(因为类定义中的self 是类对象本身)。您尝试的存根在ApplicationController 的任何实例上存根set_headers,但它不是ApplicationController 的实例方法。

      我不能真正推荐如何实现您想要做的事情,因为不清楚您想要做什么。

      【讨论】:

      • 我更新了self.set_headers,以便您更好地了解我想要完成的工作。谢谢
      • 我仍然不清楚你为什么要存根这个方法。仅当在执行示例期间调用该方法时,对方法进行存根才有效。 set_headers 在任何示例中都不会被调用,因为它是在定义类时调用的。存根它没有任何意义。
      猜你喜欢
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      • 2011-08-06
      • 1970-01-01
      • 2012-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多