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

如何在RSpec 3.12请求测试中验证redirect_back跳转?

问题

我的应用将治疗项(treatments)管理为任务列表,任务从治疗项的Show视图唤起的模态窗口创建和编辑。关闭任务表单时,我使用redirect_back跳转回治疗项页面,以root_path作为 fallback 地址:

def update    
  @task.updated_by = current_login    
  respond_to do |format|
    if @task.update_attributes(task_params)
      format.html { redirect_back fallback_location: root_path, notice: t('.Success') } 
      format.json { head :no_content }
    else
      format.html { redirect_back fallback_location: root_path, notice: "#{t('.Failure')}: #{@task.errors.full_messages.join(',')}" }
      format.json { render json: @task.errors, status: :unprocessable_entity }
    end
  end
end

但使用RSpec测试时总是报错,因为实际跳转至root_path:

describe "update - PATCH /tasks/:id" do
  context "with valid parameters" do
    let(:new_attributes) do 
      {
        sort_code: "RSPEC-Updated"
      }
    end
    it "updates the requested task" do
      patch task_url(task), params: { 
        task: new_attributes 
      }.merge(extra_fields)
      expect(response).to redirect_to(treatment_url(task.parent))
    end
  end
end

请问如何配置测试,使其跳转到预期的治疗项页面并通过测试?

解决方案

问题核心是redirect_back依赖请求中的Referer HTTP头确定跳转目标,而RSpec测试发起请求时默认不会携带该头,因此触发 fallback 跳转至root_path。以下两种方式可解决:

方式一:在测试请求中添加Referer头

直接在patch请求里携带HTTP_REFERER头,指定来源为目标治疗项页面:

it "updates the requested task" do
  patch task_url(task), 
        params: { task: new_attributes }.merge(extra_fields),
        headers: { "HTTP_REFERER" => treatment_url(task.parent) }
  expect(response).to redirect_to(treatment_url(task.parent))
end

方式二:修改控制器逻辑,直接跳转至治疗项页面

既然任务始终关联治疗项(存在parent关联),可跳过Referer头依赖,直接跳转至对应治疗项页面,逻辑更稳定且无需额外配置测试:

def update    
  @task.updated_by = current_login    
  respond_to do |format|
    if @task.update_attributes(task_params)
      format.html { redirect_to @task.parent, notice: t('.Success') } 
      format.json { head :no_content }
    else
      format.html { redirect_to @task.parent, notice: "#{t('.Failure')}: #{@task.errors.full_messages.join(',')}" }
      format.json { render json: @task.errors, status: :unprocessable_entity }
    end
  end
end

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 06:33:21