18

如何使用 Webmock 对任何正文和标头的请求进行存根?我尝试使用正则表达式

WebMock.stub_request(:post, 'api.quickblox.com/').with(:body => /.*?/, :headers => /.*?/).to_return(:status => 201, :body => "", :headers => {})

在 rspec 但它不起作用,它有

NoMethodError:
   undefined method `map' for /.*?/:Regexp
4

2 回答 2

16

你应该可以使用

WebMock.stub_request(:post, 'api.quickblox.com/')
  .to_return(status: 201, body: 'whatever', headers: { some_kind_of: 'header' })

如果您没有在存根本身上指定正文或标题,它将允许正文或标题的任何内容。这不适用于查询参数。

例如,此示例项目的测试通过:

bundle exec rspec输出:

Test
  does a thing

Finished in 0.00379 seconds (files took 0.25797 seconds to load)
1 example, 0 failures

库/test.rb

require 'faraday'
require 'json'

class Test
  def self.do_a_thing
    JSON.parse(Faraday.get('http://www.example.com') do |request|
      request.headers['Something'] = 'anything'
      request.body = 'bla bla bla'
    end.body)
  end
end

规范/test_spec.rb

require_relative '../lib/test.rb'
require 'webmock/rspec'

describe Test do
  WebMock.stub_request(:get, 'http://www.example.com')
    .to_return(body: '{ "this": "is a test" }')

  it 'does a thing' do
    expect(described_class.do_a_thing).to include({ 'this' => 'is a test' })
  end
end

.ruby 版本

ruby-2.0.0

宝石文件

gem 'rspec'
gem 'webmock'
gem 'faraday'

Gemfile.lock

GEM
  specs:
    addressable (2.3.8)
    crack (0.4.2)
      safe_yaml (~> 1.0.0)
    diff-lcs (1.2.5)
    faraday (0.9.1)
      multipart-post (>= 1.2, < 3)
    multipart-post (2.0.0)
    rspec (3.2.0)
      rspec-core (~> 3.2.0)
      rspec-expectations (~> 3.2.0)
      rspec-mocks (~> 3.2.0)
    rspec-core (3.2.3)
      rspec-support (~> 3.2.0)
    rspec-expectations (3.2.1)
      diff-lcs (>= 1.2.0, < 2.0)
      rspec-support (~> 3.2.0)
    rspec-mocks (3.2.1)
      diff-lcs (>= 1.2.0, < 2.0)
      rspec-support (~> 3.2.0)
    rspec-support (3.2.2)
    safe_yaml (1.0.4)
    webmock (1.20.4)
      addressable (>= 2.3.6)
      crack (>= 0.3.2)

PLATFORMS
  ruby

DEPENDENCIES
  faraday
  rspec
  webmock

BUNDLED WITH
   1.10.5
于 2015-06-10T21:14:03.350 回答
4

查看Webmock上的文档headers。您需要为它提供一个哈希,其中包含有关您匹配的内容的更多详细信息。

于 2014-04-19T05:42:17.593 回答