Grape/Rails维护模式下Rspec跨端点测试路由错误问询
解决MaintenanceModeController测试中的ActionController::UrlGenerationError问题
遇到这个路由错误,大概率是要么你请求的端点没在测试环境里配置,要么测试时的维护模式逻辑干扰了路由匹配,下面给你一步步拆解解决方案:
先排查路由是否真的存在
首先你得确认/api/v1/new_endpoint在测试环境的路由表里有记录。在终端跑这个命令:
rails routes -e test
如果找不到这个端点的话,先去config/routes.rb里补全路由定义,比如:
namespace :api do namespace :v1 do get 'new_endpoint', to: 'your_controller#your_action' end end
注意别把这个路由用if Rails.env.production?这类条件包裹住,不然测试环境加载不到。
测试里临时绕过维护模式(按需)
如果你的测试目标不是验证重定向逻辑,只是需要临时访问其他端点做对比,那可以在测试块里临时禁用维护模式:
describe MaintenanceModeController do context "when accessing other endpoints temporarily" do before do # 假设你的维护模式是通过ApplicationController里的maintenance_mode?方法判断的 allow_any_instance_of(ApplicationController).to receive(:maintenance_mode?).and_return(false) end it "can hit /api/v1/new_endpoint without routing errors" do get '/api/v1/new_endpoint' expect(response).to have_http_status(:ok) # 根据你的预期调整状态码 end end end
这样就能跳过维护模式的重定向,让请求正常匹配到目标路由。
测试重定向逻辑时用路由辅助方法
如果你是想验证维护模式下访问该端点会跳转到维护页,别硬写URL,用Rails生成的路由辅助方法更靠谱,避免拼写错误:
it "redirects to maintenance page when accessing api endpoint" do # 比如对应的路由辅助方法是api_v1_new_endpoint_path get api_v1_new_endpoint_path expect(response).to redirect_to(maintenance_mode_path) end
要是这个辅助方法不存在,还是回到第一步检查路由配置的问题。
强制刷新测试环境路由
有时候测试环境会缓存旧的路由,导致新添加的端点不生效,可以在测试文件开头加一段强制重载路由的代码:
before(:all) do Rails.application.reload_routes! end
临时模拟路由(快速测试用)
如果你只是想模拟请求某个端点,不想修改实际路由文件,可以在测试里临时定义一个极简路由:
before do Rails.application.routes.draw do get '/api/v1/new_endpoint', to: proc { [200, {}, ['OK']] } end end after do Rails.application.reload_routes! # 测试结束后恢复原路由 end
内容的提问来源于stack exchange,提问作者mr_muscle
相关产品推荐
相关产品推荐

