【问题标题】:Stub super method in controller控制器中的存根超级方法
【发布时间】:2014-10-08 19:12:46
【问题描述】:

如何从包含的模块中存根 :super 方法。我有以下控制器:

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 模块:

module ImportBackend
  def import_from_file
    //something
  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)

感谢所有回答。

【问题讨论】:

    标签: rspec super stub


    【解决方案1】:

    在 Ruby 中 super 看起来像一个方法,但它实际上是一个具有特殊行为的关键字(例如,supersuper() 做不同的事情,与其他所有 Ruby 方法不同),你不能存根它.

    您真正想要做的是存根super 调用的方法,在本例中为ImportBackend#import_from_file。由于它是来自模块(而不是超类)的 mixin,因此您不能以通常的方式对其进行存根。但是,您可以定义一个具有您想要的模拟行为的虚拟模块,并在您的类中定义include。这是因为当多个模块定义一个 mixin 时,super 将调用最后一个包含的模块。你可以read more about this approach here。在你的情况下,它看起来像这样:

    mock_module = Module.new do
      def import_from_file
        raise Transfer::Error
      end
    end
    
    controller.singleton_class.send(:include, mock_module)
    

    根据您的其他规格,这可能会给拆解带来一些复杂性,但我希望它可以帮助您入门。

    【讨论】:

    • 它对我不起作用。我想存根 ImportBackend#import_from_file。我使用了您的解决方案,但测试仍然失败。
    • 对不起,@user2239655,我误读了你的问题。我已经更新了我的答案。
    猜你喜欢
    • 2013-07-28
    • 2013-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多