Stubbed request not allowing http connections (Real HTTP connections are disabled.)

1.1k Views Asked by At

I am trying to stub a POST request to an external API. The spec test does not replace the ENV variable with my fake one and goes to my local env (localhost:3000) in the stub request returning this error:

Failure/Error: response = http.request(request)
     
WebMock::NetConnectNotAllowedError:
 Real HTTP connections are disabled. Unregistered request: POST http://localhost:3000/Target with body '{"name":"Wayfarer"}' with headers {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent'=>'Ruby'}
     
You can stub this request with the following snippet:
     
stub_request(:post, "http://localhost:3000/Target").
  with(
    body: "{\"name\":\"Wayfarer\"}",
    headers: {
          'Accept'=>'*/*',
          'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
          'User-Agent'=>'Ruby'
           }).
    to_return(status: 200, body: "", headers: {})

My test is:

  let!(:user) { create(:user, target: 'Wayfarer') }

  before(:each) do
    allow(ENV).to receive(:fetch).with('API_METADATA_URL').and_return('http://example.com')
  end

  describe '#create_target' do
    context 'successful API request to create target' do
      it 'sends data to API and sets response instance variables' do
        target = user.target

        stub_request(:post, 'http://example.com/Target').with(
          headers: {
          },
          body: '{
            "name": "Wayfarer"
          }'
        ).to_return(
            status: 200,
            body: '{"id": "uuid",' \
                  '"name": "Wayfarer",' \
                  '"created_at": 00000,' \
                  '"updated_at": 00000}'
          )

          api_client = ApiClient.new
          api_client.create_target(target)

          expect(api_client.response_status).to eq(200)
          expect(api_client.response_body).to eq(
            {
              'id' => 'uuid',
              'name' => 'Wayfarer',
              'created_at' => 00000,
              'updated_at' => 00000
            }
          )
      end
    end
  end

It doesn't even reach the test, instead it seems to run the ApiClient as is including using my local environment variable (as stated above).

1

There are 1 best solutions below

0
On

I ended up needing a separate .env file for tests (.env.test.local) for the API_METADATA_URL for a url that did not throw the error.