具有任何正文和标题的Webmock存根请求

时间:2014-04-18 18:03:49

标签: ruby-on-rails rspec webmock

如何使用Webmock与任何正文和标题存根请求?我试图使用正则表达式

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

但它没有用,它有

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

2 个答案:

答案 0 :(得分:11)

您应该可以使用

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

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

规格/ 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

的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

答案 1 :(得分:5)

查看Webmock docs on headers。您需要提供一个散列,其中包含有关您匹配内容的更多详细信息。