Rspec 控制器中的存根超方法
如何存根:包含模块中的超级方法。我有以下控制器:Rspec 控制器中的存根超方法,rspec,super,stub,Rspec,Super,Stub,如何存根:包含模块中的超级方法。我有以下控制器: class ImportsController < BaseController include ImportBackend def import_from_file super rescue TransferPreview::Error => exc flash[:error] = "Some String" redirect_to imports_path end end 我想测试一下
class ImportsController < BaseController
include ImportBackend
def import_from_file
super
rescue TransferPreview::Error => exc
flash[:error] = "Some String"
redirect_to imports_path
end
end
我想测试一下那个控制器。我的问题是如何在ImportBackend中存根方法以引发错误?我尝试了两种解决方案,但均无效:
ImportBackend.stub(:import_from_file).and_raise(Transfer::Error)
controller.stub(:super).and_raise(Transfer::Error)
controller.stub(:import_from_file).and_raise(Transfer::Error)
谢谢大家的回答。在Ruby中
super
看起来像是一个方法,但实际上它是一个具有特殊行为的关键字(例如,super
和super()
做不同的事情,不同于其他Ruby方法),并且您不能将其存根
您真正想要做的是存根super
调用的方法,在本例中是ImportBackend\import\u from\u file
。因为它是来自模块(而不是超类)的混合,所以不能以通常的方式对其进行存根。但是,您可以定义一个具有所需模拟行为的虚拟模块,并将其包含在类中。这是因为当多个模块定义一个mixin时,super
将调用包含的最后一个模块。你可以。在您的情况下,它看起来是这样的:
mock_module = Module.new do
def import_from_file
raise Transfer::Error
end
end
controller.singleton_class.send(:include, mock_module)
根据您的其他规格,这可能会给拆卸带来一些复杂问题,但我希望它能帮助您开始。这对我不起作用。我想要存根ImportBackend#从_文件导入_。我使用了你的解决方案,但测试仍然失败。对不起,@user2239655,我误读了你的问题。我已经更新了我的答案。
mock_module = Module.new do
def import_from_file
raise Transfer::Error
end
end
controller.singleton_class.send(:include, mock_module)