存根请求不允许 http 连接禁用真正的 HTTP 连接

问题描述

我正在尝试将 POST 请求存根到外部 API。规范测试不会用我的假变量替换 ENV 变量,而是在返回此错误的存根请求中转到我的本地环境 (localhost:3000):

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'=>'*/*','User-Agent'=>'Ruby'
           }).
    to_return(status: 200,body: "",headers: {})

我的测试是:

  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

它甚至没有通过测试,反而似乎运行了 ApiClient,包括使用我的本地环境变量(如上所述)。

解决方法

我最终需要一个单独的 .env 文件用于测试 (.env.test.local) 的 API_METADATA_URL 用于未引发错误的网址。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...