【问题标题】:How to mock my superclass in rspec如何在 rspec 中模拟我的超类
【发布时间】:2015-12-05 10:35:43
【问题描述】:

我有以下代码:

class Blurk
  def initialize
    # horror
  end

  def perform
    # yet more horror
  end
end

class Grunf < Blurk
   def perform
     super
     # here some code to test
   end
end

我想在Grunf#perform 上测试代码,但我不知道如何模拟Blurk。

【问题讨论】:

  • 您可以在测试Grunf 时重新定义Blurk#perform,或者(我认为,更好),您可以将Blurk 作为一个单元进行测试,并将Grunf 也作为一个单元进行测试。也就是说,不假设它是否是其他东西的子类,而是假设“其余部分是有效的”。
  • 在RSpec中,你也可以尝试allow().to_receive().and_return()的组合来控制对super的调用。

标签: ruby rspec3


【解决方案1】:

一般来说你不应该这样做。更好的方法(恕我直言)是对您的类定义进行一些细微的更改

class Blurk
  def initialize
    # horror
  end

  def perform
    # yet more horror
    exec_perform
  end
  
  protected
  
  def exec_perform
    raise "exec_perform must be overriden"
  end
end

class Grunf < Blurk
   def exec_perform
     # here some code to test
   end
end

并分别测试Blurk 和Grunf(在Blurk 测试中,您可以创建TestClass 定义以确认exec_perform 是否按预期运行)。在Grunf 的测试文件中,您只需测试exec_perform 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 2021-11-27
    • 1970-01-01
    • 2012-01-05
    相关资源
    最近更新 更多