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

Rails控制器Create动作Rspec测试重定向时不通过求助

问题排查与解决方案

问题原因

你使用expect(response).to be_successful断言,但控制器执行redirect_to后返回的是3xx重定向状态码(通常为302),而be_successful仅对200-299范围的状态码返回true,这就是测试失败的核心原因。尽管记录已成功创建,但测试断言的逻辑与实际响应类型不匹配。

修正后的测试代码

将测试断言替换为重定向相关验证,以下是几种可行写法:

写法1:直接验证重定向到目标详情页

it 'redirects to show badge' do
  post :create, params: { living_muay_thai_badge: valid_attributes }
  # 验证重定向到刚创建的badge详情页
  expect(response).to redirect_to(living_muay_thai_badge_path(LivingMuayThai::Badge.last))
end

写法2:验证响应是重定向状态

it 'redirects to show badge' do
  post :create, params: { living_muay_thai_badge: valid_attributes }
  # 检查是否为重定向响应
  expect(response).to be_redirect
  # 可选:同时验证flash提示
  expect(flash[:notice]).to eq("You created a new Badge record")
end

写法3:验证状态码

it 'redirects to show badge' do
  post :create, params: { living_muay_thai_badge: valid_attributes }
  # 重定向的标准状态码是302
  expect(response.status).to eq(302)
end

额外优化建议

为让测试更健壮,可同时验证记录是否成功创建:

it 'creates a badge and redirects to show page' do
  expect {
    post :create, params: { living_muay_thai_badge: valid_attributes }
  }.to change(LivingMuayThai::Badge, :count).by(1)
  
  expect(response).to redirect_to(living_muay_thai_badge_path(LivingMuayThai::Badge.last))
  expect(flash[:notice]).to eq("You created a new Badge record")
end

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 05:22:33