有没有办法检查一个方法是否被 RSpec 存根?

p.m*_*los 5 rspec

主要用于测试调试目的,我想知道是否有办法判断一个方法是否被存根。

例如,在我的一项测试中,我写道:

Model.any_instance.stub(:method)
Run Code Online (Sandbox Code Playgroud)

当我有一个真实的实例时,我想写一些类似的东西:

an_instance_of_model.stubbed?(:method) # expecting to return true
Run Code Online (Sandbox Code Playgroud)

Laz*_*dis 4

如果您已使用方法在类级别中存根any_instance方法,您可以在测试中使用类似以下内容进行检查:

RSpec::Mocks.space.any_instance_recorder_for(YourClass).already_observing?(:method_name)
Run Code Online (Sandbox Code Playgroud)

但如果您对特定实例进行了存根,则可以使用以下命令找到这一点:

!(your_instance.method(:method_name).owner >= your_instance.class)
Run Code Online (Sandbox Code Playgroud)

因此,您也可以将这些组合到辅助模块中:

module Helpers
  def stubbed?(object, method)
    RSpec::Mocks.space.any_instance_recorder_for(object.class).already_observing?(method) || !(object.method(method).owner >= object.class)
  end
end
Run Code Online (Sandbox Code Playgroud)

并将其包含在您的 RSpec.configure 中:

require 'helpers'
RSpec.configure do |config|
  ...
  config.include Helpers
  ...
end
Run Code Online (Sandbox Code Playgroud)

注意:此内容已根据@PJSCOpeland 的评论进行了更新。如果您使用的 RSpec 版本低于 3.6,请删除调用.space,即RSpec::Mocks.any_instance_recorder_for(YourClass).already_observing?(:method_name)

  • 在 RSpec 3.6+ 中尝试 `RSpec::Mocks` **`.space`** `.any_instance_recorder_for`。 (3认同)