在 rspec 中存根未实现的方法 [英] Stub unimplemented method in rspec

查看:43
本文介绍了在 rspec 中存根未实现的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试我的模块,我决定用匿名类来测试它:

I'm testing my module and I decided to test it versus anonymous class:

  subject(:klass) { Class.new { include MyModule } }

MyModuleklass 中使用方法 name.为了让我的规范工作,我需要存根这个方法 name (这是未实现的).所以我写道:

MyModule uses method name inside klass. To let my specs work I need to stub this method name (which is unimplemented). So I wrote:

subject { klass.new }
allow(subject).to receive(:name).and_return('SOreadytohelp') }

但它引发了:

 RSpec::Mocks::MockExpectationError: #<#<Class:0x007feb67a17750>:0x007feb67c7adf8> does not implement: name
from spec-support-3.3.0/lib/rspec/support.rb:86:in `block in <module:Support>'

如何在不定义的情况下存根这个方法?

how to stub this method without defining it?

推荐答案

RSpec 引发此异常,因为将原始对象上不存在的方法存根是没有用的.

RSpec raises this exception because it is not useful to stub a method that does not exist on the original object.

模拟方法总是容易出错,因为模拟的行为可能与原始实现不同,因此即使原始实现会返回错误(或什至不存在),规范也可能成功.允许模拟不存在的方法是完全错误的.

Mocking methods is always error-prone because the mock might behave differently than the original implementation and therefore specs might be successful even if the original implementation would have returned an error (or does not even exist). Allowing to mock non-existing methods is just plain wrong.

因此我认为你不应该试图绕过这个异常.只需在您的类中添加一个 name 方法,如果在测试环境之外运行,则会引发明显的异常:

Therefore I would argue that you should not try to bypass this exception. Just add a name method to your class that raises a clear exception if run outside of the test environment:

def self.name
  raise NoMethodError  # TODO: check specs...
end

这篇关于在 rspec 中存根未实现的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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