2

私はいくつかの仕様を書き、VCR gem を使用してリクエストをモックアウトしようとしている API を持っています。私が抱えている問題は、API が空のボディを返すと、Ruby がこれを空の文字列として解釈することです。ただし、VCR を使用してカセットを生成し、API 要求をモックアウトすると、nil. 要求を空の文字列に戻すコードを簡単に記述しresp = '' if resp.nil?たり、条件付きでresp.nil? || resp.empty?アクティブ サポートの処理方法に関するコード#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