2013-03-13 27 views
4

我一直在嘗試使用webmock存根多部分請求一段時間,並沒有找到一個令人滿意的解決方案。存根webmock/rspec存根多部分請求

理想情況下,我想存根要求如下:

stub_request(:post, 'http://test.api.com').with(:body => { :file1 => File.new('filepath1'), file2 => File.new('filepath2') }) 

然而,這似乎並沒有工作和RSpec抱怨該請求沒有被掐滅。打印非殘留請求:

stub_request(:post, "http://test.api.com"). 
    with(:body => "--785340\r\nContent-Disposition: form-data; name=\"file1\"; filename=\"filepath1\"\r\nContent-Type: text/plain\r\n\r\nhello\r\n--785340\r\nContent-Disposition: form-data; name=\"file2\"; filename=\"filepath2\"\r\nContent-Type: text/plain\r\n\r\nhello2\r\n--785340\r\n", 
      :headers => {'Accept'=>'*/*; q=0.5, application/xml', 'Accept-Encoding'=>'gzip, deflate', 'Content-Length'=>'664', 'Content-Type'=>'multipart/form-data; boundary=785340', 'User-Agent'=>'Ruby'}). 
    to_return(:status => 200, :body => "", :headers => {}) 

當然,由於邊界是動態生成的,因此我無法真正遵循此建議。任何想法如何我可以妥善存根這些請求?

謝謝! Bruno

回答

2

WebMock目前不支持多部分請求。這裏查看作者的評論更多信息:https://github.com/vcr/vcr/issues/295#issuecomment-20181472

我建議你考慮以下途徑之一:

  • 存根沒有後多體
  • 包裹,文件路徑參數和方法的要求相匹配設置使用錄像機進行集成嘲諷外部請求這種方法
  • 更細粒度的期望測試
2

有點遲了,但我會留下未來的溢出者和谷歌的答案。

我有同樣的問題,並與Webmock一起使用Rack::Multipart::Parser作爲解決方法。快速和骯髒的代碼應該是這個樣子(警告:使用的ActiveSupport擴展):

stub_request(:post, 'sample.com').with do |req| 
    env = req.headers.transform_keys { |key| key.underscore.upcase } 
        .merge('rack.input' => StringIO.new(req.body)) 
    parsed_request = Rack::Multipart::Parser.new(env).parse 

    # Expectations: 
    assert_equal parsed_request["file1"][:tempfile].read, "hello world" 
end 
0

下面是使用WebMock用正則表達式匹配的multipart/form-data的請求一種變通方法,對圖像的測試上傳特別方便:

stub_request(:post, 'sample.com').with do |req| 

    # Test the headers. 
    assert_equal req.headers['Accept'], 'application/json' 
    assert_equal req.headers['Accept-Encoding'], 'gzip, deflate' 
    assert_equal req.headers['Content-Length'], 796588 
    assert_match %r{\Amultipart/form-data}, req.headers['Content-Type'] 
    assert_equal req.headers['User-Agent'], 'Ruby' 

    # Test the body. This will exclude the image blob data which follow these lines in the body 
    req.body.lines[1].match('Content-Disposition: form-data; name="FormParameterNameForImage"; filename="image_filename.jpeg"').size >= 1 
    req.body.lines[2].match('Content-Type: img/jpeg').size >= 1 

end 

只測試頭部也可以使用正常的WebMock方式使用stub_request(:post, 'sample.com').with(headers: {'Accept' => 'application/json}),並且在with子句中不包含任何主體規範。