Search code examples
rubyrspecrspec-mocks

Issue with spies in Rspec


Having trouble figuring out why:

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

results in:

"Failure/Error: expect(arr.store).to have_received(:[]=).exactly(8).times # expected to have received []=, but that object is not a spy or method has not been stubbed."


Solution

  • Not exactly sure what your code is doing, but my suspicion is that calling arr.send(:store) returns a different object each time. Try modifying like this:

    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