有没有办法检查一个方法是否被 RSpec 存根? [英] Is there a way to check whether a method is stubbed with RSpec?

查看:33
本文介绍了有没有办法检查一个方法是否被 RSpec 存根?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Mainly for test debugging purposes, I would like to know whether there is a way to tell whether a method is stubbed or not.

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

For example, in one of my tests, I write:

Model.any_instance.stub(:method)

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

And when I have a real instance I want to write something like:

an_instance_of_model.stubbed?(:method) # expecting to return true

推荐答案

如果您使用 any_instance 方法在类级别中存根了方法,您可以使用在你的测试中是这样的:

In case you have stubbed the method in class level with the any_instance method you may check this using something like this in your test:

RSpec::Mocks.space.any_instance_recorder_for(YourClass).already_observing?(:method_name)

但如果您存根特定实例,您可以使用以下方法找到:

but if you stubbed a specific instance, you can find this out by using the following:

!(your_instance.method(:method_name).owner >= your_instance.class)

所以你也可以在一个辅助模块中组合这些:

So you may combine these too in a helper module:

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

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

and include it in your RSpec.configure:

require 'helpers'
RSpec.configure do |config|
  ...
  config.include Helpers
  ...
end

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

NB: This has been updated based on @PJSCopeland's comment. If you're using a version of RSpec less than 3.6, remove the .space calls, i.e. RSpec::Mocks.any_instance_recorder_for(YourClass).already_observing?(:method_name)

这篇关于有没有办法检查一个方法是否被 RSpec 存根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆