2

我有一个 API,我正在尝试编写一些规范并使用 VCR gem 模拟请求。我遇到的问题是,当 API 返回一个空主体时,Ruby 将其解释为一个空字符串。但是,当我使用 VCR 生成磁带来模拟 API 请求时,它会返回nil. 我可以轻松地围绕这个编写代码,将请求修改回空字符串resp = '' if resp.nil?,或者有条件地编写关于如何在时机成熟resp.nil? || resp.empty?或 Active Supports时处理它的代码,#blank?但我宁愿不必编写代码来简单地满足我的规范。

test_spec.rb

require 'net/http'
require 'vcr'
require 'syck'


def vcr_test
  uri_host = 'www.mocky.io'
  uri_port = 80
  route = '/v2/562e9e7f1100001236933b4b'
  http = Net::HTTP.new(uri_host, uri_port)
  resp = http.get(route)
  resp.body
end

VCR.configure do |c|
  c.cassette_library_dir = 'spec/support/vcr'
  c.hook_into :webmock
  c.configure_rspec_metadata!
  c.default_cassette_options = { :record => :once }
  c.allow_http_connections_when_no_cassette = false
  c.ignore_localhost = false
  c.ignore_hosts 'codeclimate.com'
end

context '#vcr_test' do
  it 'should not return nil' do
    VCR.use_cassette('vcr_test') do
      expect(vcr_test).to eq('')
    end
  end
end

vcr_test.yml

---

http_interactions: 
- request: 
    method: get
    uri: http://www.mocky.io/v2/562e9e7f1100001236933b4b
    body: 
      encoding: US-ASCII
      string: ""
    headers: 
      Accept-Encoding: 
      - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
      Accept: 
      - "*/*"
      User-Agent: 
      - Ruby
  response: 
    status: 
      code: 200
      message: OK
    headers: 
      Server: 
      - Cowboy
      Connection: 
      - close
      Content-Type: 
      - application/json; charset=utf-8
      Date: 
      - Mon, 26 Oct 2015 21:52:19 GMT
      Via: 
      - 1.1 vegur
    body: 
      encoding: UTF-8
      string: ""
    http_version: 
  recorded_at: Mon, 26 Oct 2015 21:52:19 GMT
recorded_with: VCR 2.9.3

在录制磁带之前

$ rspec test_spec.rb

Finished in 0.3623 seconds (files took 0.44012 seconds to load)
1 example, 0 failures

录制磁带后

$ rspec test_spec.rb

Failures:

  1) #vcr_test should not return nil
     Failure/Error: expect(vcr_test).to eq('')

       expected: ""
            got: nil

       (compared using ==)
     # ./test_spec.rb:28:in `block (3 levels) in <top (required)>'
     # ./test_spec.rb:27:in `block (2 levels) in <top (required)>'

Finished in 0.03411 seconds (files took 0.32761 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./test_spec.rb:26 # #vcr_test should not return nil

如何让 VCR 复制空主体的实际响应?

4

0 回答 0