我有一个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复制空体的实际响应?