jeudi 7 novembre 2019

How do I convert an `expect_any_instance_of()` (as it is deprecated) so my rspec tests still pass?

From the rspec documentation, expect_any_instance_of() has been deprecated. What I haven't found so far, though, is an easy way to replace that method with another. Everything I've tried so far fails and especially, the method that is expected to be mocked gets called.

context 'test Foo' do
  before(:each) do
    info = double(
      size: 12345,
      close: true
    )
    allow(Blah).to receive(:open).and_return(info)  # this one works
  end                                                                       

  it 'returns false on failure' do
    # This expect_any_instance_of() works like a charm
    expect_any_instance_of(MyUploader).to receive(:process_with_some_tool).and_return(false)

    uploader = MyUploader.new(create(:my_object, data: nil))

    # These expect()'s fails
    expect(MyUploader).to receive(:process_with_some_tool).and_return(true)
    expect(uploader).to receive(:process_with_some_tool).and_return(true)

    uploader.store!(trigger_data)
  end
end

The first expect(MyUploader) (so with the class name), I also tried to place inside the before block. I kind of was expecting it to fail anyway since the class name of the uploader object looks like this on a run (and of course the number changes on each run):

MyUploader::Uploader47181996911040

However, I don't understand why the expect(uploader) (so with the object I just allocated) fails too. Since I'm attached to the very object I created, why wouldn't it have that :process_with_some_tool event mocked and just return true?

I have a puts "CALLED\n" in my :process_with_some_tool and I see that message when I use the expect(). I do not see it when I use the expect_any_instance_of(). So the former doesn't mock anything and the latter mocks as expected...

I also tried to wrap my head around the Method stubs help page, but again, I've not been able to make it work.

So my question is: how do we transform an expect_any_instance_of() so it actually works?

Note: I'm new to Ruby, Rails, RSpec and all of that. I suspect it's an easy one but I just don't see how to make it all work...

Aucun commentaire:

Enregistrer un commentaire