我正在使用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字段=名称,类型和安培;深度= 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'})
我使用的正则表达式是正确的,但我不明白为什么我收到此错误信息。
答案 0 :(得分:0)
您的要求是:
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])?}