微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决存根请求不允许 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 用于未引发错误的网址。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。