0

I got a cucumber step defined as follows:

When(/^I click on the button to create a new target$/) do
  RSpec::Mocks.with_temporary_scope do
    dummy_connection = double('Dummy connection')
    allow(dummy_connection).to receive(:add_target)
                           .and_return({ target_id: "ABCD" }.to_json)

    allow(MyConnection).to receive(:retrieve_connection).and_return dummy_connection

    click_button "Create"
  end
end

In my controller I have a small class which proxies the original library class:

class MyConnection
  def self.retrieve_connection
    Vws::Api.new(KEY, SECRET)
  end
end

While executing the test, "MyConnection.retrieve_connection" tries to connect to the web service, even if it's stubbed out. However if in the test I write

MyConnection.retrieve_connection.inspect => #<Double "Dummy connection">

So MyConnection.retrieve_connection returns the dummy connection, which is correct. It just doesn't work in the controller.

I'm out of ideas, it simply doesn't seem to work. Any hint?

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
c0m3tx
  • 98
  • 1
  • 7

1 Answers1

0

Found out that I have to apply mocks in a Cucumber Before block to make it work.

However, since MyConnection class only gets defined after loading the controller for the first time, I had to mock directly the library function:

Before do
  dummy_connection = double("Dummy connection")
  allow(dummy_connection).to receive(:add_target).and_return({ target_id: SecureRandom.hex(4) }.to_json)
  allow(Vws::Api).to receive(:new).and_return(dummy_connection)
end

in a cucumber hooks file features/env/hooks.rb.

This way it seems to work every time.

c0m3tx
  • 98
  • 1
  • 7