如何只测试RSpec中的多个方法调用之一?

问题描述

def some_method
  subject.put(1)
  subject.put(2)
  ...
end

由于对put调用不止一次,因此以下操作失败,是否可以仅验证发生的第一个调用不关心其余调用

expect(subject).to receive(:put).with(1).once

解决方法

玩了一会儿,以下内容起作用了。

allow(subject).to receive(:put)
expect(subject).to receive(:put).with(1).once
,

通常,您需要将设置和期望分开,例如:

before do
  allow(subject).to receive(:put)
end

it 'invokes put' do
  expect(subject).to receive(:put).with(1).once
end