2015-02-24 39 views
0

我正在使用rspec和webmock,並且正在研究stubbing請求。我嘗試使用正則表達式來匹配URI時遇到問題。Ruby - 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

你得請求爲:

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

你給了正則表達式: 「\」

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

在正則表達式,你已經與指定的強制要求應該包含「?」 (或一個查詢)在「insertion_order/\ w +」之後。在請求中你沒有任何查詢參數。這就是爲什麼它不符合要求。

您可以修復的一種方法是使可選「regexp」中的「insertion_order/\ w +」之後出現的部分。我會這樣做:

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

嘿@Iimekin感謝這一點,但實際上它並沒有解決問題。我是否應該完成正則表達式以匹配https://mocktocapture.com/mgmt? – AlessioG 2015-02-24 11:25:41

+0

是的,如果你想匹配,你應該完成它。 – limekin 2015-02-24 11:44:30