Rspec 中的间谍问题

Issue with spies in Rspec

无法找出原因:

it "shifts/unshifts without O(n) copying" do
  arr = RingBuffer.new

  allow(arr.send(:store)).to receive(:[]=).and_call_original
  8.times do |i|
    arr.unshift(i)
  end

  # Should involve 8 sets to unshift, no more.
  expect(arr.send(:store)).to have_received(:[]=).exactly(8).times
end

结果:

"Failure/Error: expect(arr.store).to have_received(:[]=).exactly(8).times # 预期已收到 []=,但该对象不是间谍或方法尚未存根。"

不确定您的代码在做什么,但我怀疑每次调用 arr.send(:store) returns 不同的对象。尝试这样修改:

it "shifts/unshifts without O(n) copying" do
  arr = RingBuffer.new
  store = arr.send(:store)

  allow(store).to receive(:[]=).and_call_original
  8.times do |i|
    arr.unshift(i)
  end

  # Should involve 8 sets to unshift, no more.
  expect(store).to have_received(:[]=).exactly(8).times
end