RSpec stub_request如何返回数组格式响应体解决each方法报错
问题现象
编写Rspec服务单元测试时触发报错:undefined method 'each' for "invoices":String
- 报错触发逻辑:业务方法需要遍历解析接口响应中的
invoices数组,但当前stub返回的响应中invoices被识别为字符串类型,无法执行each遍历。
关联代码
被测业务方法
def generate_invoices invoices_ids = [] response = HTTParty.get('https://books.zoho.com/api/v3/invoices?organization_id='\ "#{ENV['ZOHO_ORGANISATION_ID']}&cf_lc_contract_id_startswith=#{@contract_id}&"\ 'cf_facture_final=true', headers: { 'Authorization' => "Zoho-oauthtoken #{@access_token}" }) response.code == 200 ? response : raise_error(response.body) response['invoices'].each do |invoice| invoices_ids.push invoice['invoice_id'] end invoices_ids.join(',') end
现有stub模拟配置
stub_request(:get, 'https://books.zoho.com/api/v3/invoices?cf_facture_final=true'\ "&cf_lc_contract_id_startswith=123&organization_id=#{ENV['ZOHO_ORGANISATION_ID']}") .with(headers: { 'Authorization' => 'Zoho-oauthtoken access_token' }) .to_return(status: 200, body: { 'invoices' => [{ "invoice_id": '123' }] }.to_json, headers: {})
报错根因
stub返回响应时没有设置Content-Type: application/json响应头,HTTParty不会自动将JSON格式的响应体字符串解析为Ruby Hash结构。此时调用response['invoices']实际是在JSON字符串上按字符索引取值,拿到的是字符串"invoices",字符串类型没有数组遍历的each方法,因此触发报错。
修复方案
在stub的返回头中补充正确的JSON内容类型标识,和真实Zoho接口的响应头保持一致,让HTTParty自动完成响应体解析:
stub_request(:get, 'https://books.zoho.com/api/v3/invoices?cf_facture_final=true'\ "&cf_lc_contract_id_startswith=123&organization_id=#{ENV['ZOHO_ORGANISATION_ID']}") .with(headers: { 'Authorization' => 'Zoho-oauthtoken access_token' }) .to_return( status: 200, body: { 'invoices' => [{ "invoice_id": '123' }] }.to_json, headers: { 'Content-Type' => 'application/json' } )
调整后重新运行测试,HTTParty会自动把响应体解析为Hash结构,response['invoices']可以正常拿到数组类型数据,遍历逻辑可正常执行。
内容的提问来源于stack exchange,提问作者Wako
相关产品推荐
相关产品推荐

