4

I tried to put WebMock.disable_net_connect! in a lot of places but as recommended in my last test I put it in spec_helper.rb like this:

require 'webmock/rspec'
WebMock.disable_net_connect!(allow_localhost: true)

My spec is the following:

describe Client do
  describe '#get_something' do
    context 'when post params are valid' do
      it 'returns a response' do
        request = stub_request(:post, 'https://myurl.com')
          .to_return(my_response)

        result = client.get_something(params)

        expect(WebMock).to have_requested(:post, 'https://myurl.com')
      end
    end
  end
end

Hmm, of course that my client makes the call:

class Client
  def get_something(params)
    RestClient.post @url, params
  end
end

It fails with this message:

Failure/Error: end
       The request GET https://myurl.com/ was expected to execute 1 time but it executed 0 times

       The following requests were made:

       No requests were made.
       ============================================================

I'm using rails 4.1.8, rspec 3.1.7, rspec-rails 3.1.0 and webmock 1.8.11. Right now, I'm creating a mock of a http_client to get things working, but, any help here will be appreciated! If you need more information just let me know!

Nelson Senna
  • 626
  • 7
  • 9

2 Answers2

1

You should be using this instead:

WebMock.allow_net_connect!

Alternatively, you could also do

WebMock.disable_net_connect(allow: ['https://myurl.com'])

As shown in the documentation of WebMock:

WebMock.allow_net_connect!

stub_request(:any, "www.example.com").to_return(:body => "abc")

Net::HTTP.get('www.example.com', '/')    # ===> "abc"
Ho Man
  • 2,308
  • 11
  • 16
  • As far I understood this is the default behavior I don't even need to use `WebMock.allow_net_connect!`. I want to do the same done here: https://robots.thoughtbot.com/how-to-stub-external-services-in-tests – Nelson Senna Mar 31 '16 at 14:02
  • 1
    `WebMock.disable_net_connect(allow: ['https://myurl.com'])` will only allow https://myurl.com to pass through though? – Ho Man Apr 01 '16 at 06:09
0

Putting these two lines before making api call to external host solved the issue for me.

  WebMock.disable!
  WebMock.disable_net_connect!

See this for more details: https://github.com/bblimke/webmock/issues/897