【问题标题】:RSpec: Expecting a method to be called causes that method to not actually be calledRSpec:期望调用一个方法会导致该方法实际上没有被调用
【发布时间】:2021-11-13 06:35:02
【问题描述】:

我有一些代码可以用非常简单的术语表示:

def method_a(key)
  hash = method b(key)
  hash.delete(key) 
end

def method_b(key)
 return { key => 1 }
end

然后是 rspec 测试

it 'calls method_b'
  expect(someClass).to receive(:method_b).with(key)
  method_a(key)
end

但是,我在 method_a 的第二行中收到错误,因为它试图在 nil 对象上调用 delete。当我调试时,我可以看到 method_b 内部的逻辑实际上从未被调用过。它并没有在method_b的某个地方失败,它根本没有调用它。如果我去掉测试中的expect 语句,这个错误就会消失。似乎期望语句导致它跳过对 method_b 的实际调用,给我留下一个 nil 值而不是我期望的哈希值。

有没有办法阻止它跳过method_b,或者至少在expect语句成功后终止执行,这样我就不会在下一行遇到错误?

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

    当您设置消息期望时,它会覆盖原始代码,除非您明确告诉 RSpec 不要:

    expect(someClass).to receive(:method_b).with(key).and_call_original
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      相关资源
      最近更新 更多