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
相关产品推荐
相关产品推荐

