Rspec中的间谍问题

时间:2018-01-03 20:57:58

标签: ruby rspec rspec-mocks

无法弄清楚原因:

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

结果:

"失败/错误:期望(arr.store).to has_received(:[] =)。完全(8).times        #期望已收到[] =,但该对象不是间谍或方法尚未被删除。"

1 个答案:

答案 0 :(得分:2)

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

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