Ruby - Webmock:使用正则表达式匹配 URI

Ruby - Webmock: Match URI using regular expression

我正在使用 rspec 和 webmock,我正在调查存根请求。当我尝试使用正则表达式匹配 URI 时确实遇到了问题。

当我使用下面的存根时一切正常,没有匹配特定的 URI (/.*/)

it "returns nil and stores an error when the response code is not OK" do
      stub_request(:get, /.*/).
        with(
        :headers => insertion_api.send(:default_headers,  false).merge('User-Agent'=>'Ruby'),
        :body => {}
      ).
       to_return(
        :status => Insertion.internal_server_error.to_i,
        :body => "{\"message\": \"failure\"}",
        :headers => { 'Cookie' => [session_token] }
      )

      expect(insertion_api.get_iou(uid)).to be_nil
      expect(insertion_api.error).to eq("An internal server error occurred")
     end

由于我想在我的测试中更加具体以提高可读性,如果我尝试匹配这个特定的 URI: /insertion_order/012awQQd?fields=name,type&depth=4 使用下面的存根:

it "returns nil and stores an error when the response code is not OK" do
          stub_request(:get, %r{insertion_order/\w+\?fields\=[\w,]+\&depth\=[0-9]}).
            with(
            :headers => insertion_api.send(:default_headers,  false).merge('User-Agent'=>'Ruby'),
            :body => {}
          ).
           to_return(
            :status => Insertion.internal_server_error.to_i,
            :body => "{\"message\": \"failure\"}",
            :headers => { 'Cookie' => [session_token] }
          )

          expect(insertion_api.get_iou(uid)).to be_nil
          expect(insertion_api.error).to eq("An internal server error occurred")
         end

运行 我的测试:

WebMock::NetConnectNotAllowedError:
       Real HTTP connections are disabled. Unregistered request: GET https://mocktocapture.com/mgmt/insertion_order/0C12345678 with body '{}' with headers {'Accept'=>'application/vnd.xxx.mgmt+json; version=2.0', 'Cookie'=>'y0Urv3ryLon6s3cur1tYT0k3ng0zeh3r3', 'User-Agent'=>'Ruby'}

       You can stub this request with the following snippet:

       stub_request(:get, "https://mocktocapture.com/mgmt/insertion_order_units/0C12345678").
         with(:body => "{}",
              :headers => {'Accept'=>'application/vnd.dataxu.mgmt+json; version=2.0', 'Cookie'=>'y0Urv3ryLon6s3cur1tYT0k3ng0zeh3r3', 'User-Agent'=>'Ruby'}).
         to_return(:status => 200, :body => "", :headers => {})

       registered request stubs:

       stub_request(:get, "/insertion_order\/\w+\?fields\=[\w,]+\&depth\=[0-9]/").
         with(:body => {},
              :headers => {'Accept'=>'application/vnd.xxx.mgmt+json; version=2.0', 'Cookie'=>'y0Urv3ryLon6s3cur1tYT0k3ng0zeh3r3', 'User-Agent'=>'Ruby'})

我使用的正则表达式是正确的,但我不明白为什么会收到此错误消息。

您收到的请求是:

https://mocktocapture.com/mgmt/insertion_order/0C12345678

你已经给出了正则表达式:

%r{insertion_order/\w+\?fields\=[\w,]+\&depth\=[0-9]}

在你用“\?”指定的正则表达式中请求必须包含“?” (或查询)在 "insertion_order/\w+" 之后。在您收到的请求中没有任何查询参数。这就是它与请求不匹配的原因。

解决此问题的一种方法是将正则表达式中 "insertion_order/\w+" 之后的部分设为可选。我会这样做:

%r{insertion_order/\w+(\?fields\=[\w,]+\&depth\=[0-9])?}