Ruby非Rails项目中Rspec+WebMock测试Httparty API时参数错误
JSON.parse调用报错参数不匹配的解决方法
错误日志
Requests::FilesManager#display fetches the files from the API Failure/Error: Requests::FilesManager.new.display ArgumentError: wrong number of arguments (given 2, expected 1)
相关代码
run.rb
module Requests require "httparty" require 'json' class FilesManager include HTTParty def initialize end def display response = HTTParty.get('https://api.publicapis.org/entries', format: :json) parsed_response = JSON.parse(response.body) puts "The secret message was: #{parsed_response["message"]}" end end end
测试spec文件
require 'spec_helper' require_relative '../run' RSpec.describe Requests::FilesManager do describe "#display" do it 'fetches the files from the API' do stub_request(:get, "https://api.publicapis.org/entries"). to_return(status: 200, body: "", headers: {}) Requests::FilesManager.new.display end end end
问题定位
错误来自JSON.parse(response.body),注释该行后错误消失。核心问题有两个:
- 指定
format: :json后,HTTParty会自动将响应体解析为Ruby对象(Hash/数组),此时response.body已不是原始JSON字符串,传给JSON.parse会触发参数类型不匹配的错误。 - WebMock返回的空字符串
body: ""不是合法JSON格式,即使不依赖自动解析,直接调用JSON.parse也会失败。
解决方法
方法一:移除自动解析,手动处理原始字符串
修改run.rb的display方法,去掉format: :json参数,保留手动解析逻辑:
def display response = HTTParty.get('https://api.publicapis.org/entries') parsed_response = JSON.parse(response.body) puts "The secret message was: #{parsed_response["message"]}" end
同时更新WebMock的返回内容为合法JSON:
stub_request(:get, "https://api.publicapis.org/entries"). to_return(status: 200, body: '{"message": "test secret"}', headers: { 'Content-Type' => 'application/json' })
方法二:利用HTTParty自动解析特性
既然指定了format: :json,直接使用HTTParty已解析好的对象,无需再调用JSON.parse:
修改run.rb的display方法:
def display response = HTTParty.get('https://api.publicapis.org/entries', format: :json) parsed_response = response.parsed_response puts "The secret message was: #{parsed_response["message"]}" end
同样需要更新WebMock返回合法JSON内容:
stub_request(:get, "https://api.publicapis.org/entries"). to_return(status: 200, body: '{"message": "test secret"}', headers: { 'Content-Type' => 'application/json' })
内容的提问来源于stack exchange,提问作者josegp
相关产品推荐
相关产品推荐

