Webmock stub request with any body and header

2019-03-24 16:58发布

How to use Webmock to stub request with any body and header? I tried to use regex

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

in rspec but it doesn't work, it has

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

2条回答
可以哭但决不认输i
2楼-- · 2019-03-24 17:03

You should be able to just use

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

If you don't specify the body or headers on the stub itself, it will allow anything for the body or headers. This does not apply to query parameters.

For example, this sample project's test passes:

bundle exec rspec output:

Test
  does a thing

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

lib/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

spec/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-version

ruby-2.0.0

Gemfile

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
查看更多
不美不萌又怎样
3楼-- · 2019-03-24 17:17

Check out the Webmock docs on headers. You need to provide it a hash with further details on what you are matching.

查看更多
登录 后发表回答