[英]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.