簡體   English   中英

帶有Rspec的存根ApplicationController類方法

[英]Stub ApplicationController Class Method With Rspec

我如何在set_headers存根下面的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

剛剛對此進行了快速測試,發現它應該可以工作:

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

這里有多個問題:

  • set_headers當被調用RegularController定義。 這是在規范運行之前很長時間發生的,因此對set_headers方法進行存根將沒有任何影響。
  • 在您的RegularController類定義中, set_headers的接收者是RegularController (因為類定義內的self是類對象本身)。 您嘗試的存根是在ApplicationController任何實例上存根set_headers ,但它不是ApplicationController的實例方法。

我真的不能推薦如何實現您的目標,因為不清楚您要做什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM