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

如何编写Minitest测试正确传递JSON参数给Turbo Stream接口

问题

在Rails项目中,CartsController#update_receipt_number接口以TURBO_STREAM方式处理时,可正确接收参数:

Processing by CartsController#update_receipt_number as TURBO_STREAM
  Parameters: {"code_json_data"=>"{\"code_data\":\"69aabaa2f610860c827f27fb386d4\",\"id\":6}", "id"=>"6"}

但编写Minitest测试时使用如下代码:

post update_receipt_number_cart_url(carts(:thirty_one), format: :turbo_stream), params: { code_json_data: 
  { code_data: '69aabaa2f610860c827f27fb386d4', id: carts(:thirty_one).id } 
}, as: :json 

(已尝试添加或移除, as: :json,结果一致),测试时报错:

TypeError: no implicit conversion of ActionController::Parameters into String
    app/controllers/carts_controller.rb:192:in `update_receipt_number'

控制器第192行代码为result = JSON.parse(params[:code_json_data]),请问该如何编写测试以正确传递符合要求的JSON参数哈希?

解决方案

问题核心是测试中传递的code_json_data是哈希对象,但控制器需要的是JSON字符串——生产环境的请求里这个参数是被序列化成JSON字符串传递的,而测试直接传哈希后,Rails会把它包装成ActionController::Parameters对象,导致JSON.parse无法解析。

修改测试代码,将哈希转为JSON字符串即可,同时移除as: :json(因为要和生产环境一致,是在常规参数中传递JSON字符串,而非发送JSON格式的请求体):

post update_receipt_number_cart_url(carts(:thirty_one), format: :turbo_stream), 
     params: { 
       code_json_data: { 
         code_data: '69aabaa2f610860c827f27fb386d4', 
         id: carts(:thirty_one).id 
       }.to_json 
     }

也可以用JSON.generate替代to_json,效果一致:

post update_receipt_number_cart_url(carts(:thirty_one), format: :turbo_stream), 
     params: { 
       code_json_data: JSON.generate({ 
         code_data: '69aabaa2f610860c827f27fb386d4', 
         id: carts(:thirty_one).id 
       }) 
     }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 10:52:08