如何在 rspec 中模拟我的超类

How to mock my superclass in rspec

我有以下代码:

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

一般来说你不应该这样做。更好的方法(恕我直言)是对您的 class 定义

进行一些细微的更改
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

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