在Ruby 3.1.3和Faraday 2.7.5中,我永远无法从法拉第获得JSON响应:
def connection
@connection ||= Faraday.new(
url: url,
headers: headers
) do |faraday|
faraday.response :json
faraday.request :json
end
end
def headers
{ content_type: 'application/json',
accept: 'application/json' }
end
def send_request
connection.send(method) do |req|
req.body = body
end
end
运行时,我检查了response.body
,它从来不是JSON(即使我有faraday.response :json
:
[1] pry(#<App>)> response.body
=> "{\"data\":{\"date\":\"some_data\"}}"
我必须:
[2] pry(#<>)> JSON.parse response.body
=> {"data"=>{"date"=>"some_data"}}
我正在检查的测试是:
let(:response_body) { { data: { date: 'some_data' } }.to_json }
...
stub_request(:post, url)
.with(
body: body.to_json,
headers: custom_headers
).to_return(status: status, body: response_body, headers: {})
end
it 'POSTS to a url' do
subject
expect(a_request(:post, url)).to have_been_made
end
end
是我的测试出错了,还是客户端代码总是返回json
出错了?
1条答案
按热度按时间brqmpdu11#
我的猜测是你请求的API没有设置正确的
content-type
响应头。我没有深入研究法拉第代码,但似乎如果响应不是'application/json'格式,response.body将以普通字符串形式交付。