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

Ruby使用HTTParty报错:无法将HTTParty::Response隐式转换为String

解决TypeError:无法将HTTParty::Response隐式转换为字符串

之前正常运行的代码,现在通过注册ID查询时触发错误:

no implicit conversion of HTTParty::Response into String (TypeError)

原始代码

class Crud
  include HTTParty
  base_uri 'http://dummy.restapiexample.com/api/v1'

  def create 
    nome = Faker::UniqueGenerator.clear
    nome = Faker::Name.unique.first_name
    salario = Faker::Number.number(digits: 2)
    idade   = Faker::Number.number(digits: 2)
    $body = {name: nome, salary: salario, age: idade }.to_json

    $headers = {
      'Accept' => 'application/vnd.tasksmanager.v2',
      'Content-Type' => 'application/json'
    }

    self.class.post('/create', body: $body, headers: $headers) 
  end

  def retrieve(id)
    self.class.get("/employee/#{ id }")
  end 
  
  def delete(id)
    self.class.delete("/delete/#{ id }")
  end
end

# 测试代码部分
$response = @manter_user.create
expect(@manter_user.create.code).to eq (200)
puts $response.body
pp @id = JSON.parse($response)["id"] # 错误触发行
# no implicit conversion of HTTParty::Response into String (TypeError)
puts @manter_user.retrieve(@id)
expect(@manter_user.retrieve(@id).code).to eq (200) 

错误原因

错误出现在JSON.parse($response)这一行:$response是HTTParty返回的HTTParty::Response对象,并非字符串类型,但JSON.parse()要求传入字符串格式的参数。必须调用$response.body获取响应的文本内容,再传给JSON.parse()。

修正后的代码

# 修正后的测试代码
$response = @manter_user.create
expect($response.code).to eq(200) # 优化:避免重复调用create接口
puts $response.body
pp @id = JSON.parse($response.body)["id"] # 改为传入$response.body
puts @manter_user.retrieve(@id)
expect(@manter_user.retrieve(@id).code).to eq(200)

内容的提问来源于stack exchange,提问作者Cassia Klaison

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 12:40:28