ruby - 使用 webmock/rspec stub 多部分请求

标签 ruby rspec sinatra rest-client webmock

我一直在尝试使用 webmock 对多部分请求进行 stub ,但没有找到令人满意的解决方案。

理想情况下,我想将请求 stub 如下:

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

然而,这似乎不起作用,RSpec 提示请求没有被 stub 。打印非 stub 请求:

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 => {})

当然,我不能真正遵循这个建议,因为边界是动态生成的。知道如何正确 stub 这些请求吗?

谢谢! 布鲁诺

最佳答案

有点晚了,但我会为 future 的 overflowers 和 googlers 留下答案。

我遇到了同样的问题并使用了 Rack::Multipart::Parser结合 Webmock 作为变通方法。快速而肮脏的代码应该看起来像这样(警告:使用 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

关于ruby - 使用 webmock/rspec stub 多部分请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15375863/

相关文章:

ruby-on-rails - EC2 : Unable to rvm install ruby

ruby-on-rails - 无法验证 https ://rubygems. org/的 SSL 证书

c - Ruby 中没有操作范围?

ruby-on-rails - Rails - 测试使用 DateTime.now 的方法

ruby-on-rails - Ruby、Rspec 和 yield stub

ruby - 在生产环境中调试 Sinatra 应用程序时遇到问题

ruby - Sinatra 自定义 SASS 目录

ruby-on-rails - capybara 在功能规范期间找不到数据库记录

ruby - 如何测试在 Sinatra Controller 中调用的方法?

javascript - 简单数据图网站高流量解决方案