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

如何在Rspec控制器测试中正确测试Turbo Stream GET请求?

正确测试Turbo Stream控制器动作的Rspec方法
  • 问题根源:你当前的断言错误地将整个response对象(ActionDispatch::TestResponse实例)与Mime[:turbo_stream](Mime::Type实例)做相等比较,两者类型完全不同,必然失败。

  • 正确的请求发起方式:你写的get :index, as: :turbo_stream是正确的,as: :turbo_stream会自动设置请求格式为turbo stream,后端能正确识别该请求类型。

  • 修正后的测试代码:

describe 'GET /CONTROLLER_NAME' do
  it 'returns a turbo stream response' do
    get :index, as: :turbo_stream
    
    # 方式1:验证响应的Content-Type
    expect(response.content_type).to eq Mime[:turbo_stream].to_s
    # 也可以直接写对应的字符串值
    # expect(response.content_type).to eq "text/vnd.turbo-stream.html"
    
    # 方式2:验证响应的格式标识
    expect(response.format).to eq :turbo_stream
  end
end
  • 额外补充:如果需要验证控制器渲染了指定的turbo stream模板,可添加如下断言:
expect(response).to render_template(:index)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 23:31:46