You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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),注释该行后错误消失。核心问题有两个:

  1. 指定format: :json后,HTTParty会自动将响应体解析为Ruby对象(Hash/数组),此时response.body已不是原始JSON字符串,传给JSON.parse会触发参数类型不匹配的错误。
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 21:15:40