测试更新动作时RSpec报UrlGenerationError路由错误
问题:RSpec测试Genre更新功能触发UrlGenerationError,但实际功能正常
测试genres_controller的更新功能时,应用实际运行正常,但RSpec抛出UrlGenerationError,尝试多种方法无效,相关代码如下:
genres_spec.rb
describe "PUT genre" do it "should update genre" do request.headers["Authorization"] = "Token token=#{@token}" old_genre = Genre.find(1) patch api_v1_genre_path(1) # 试过换成带参数的'patch :update'也没用 puts response.body end end
routes.rb
Rails.application.routes.draw do namespace :api do namespace :v1 do # 基础路由 resources :users resources :studios resources :genres resources :productions resources :characters # 认证路由 post "auth", to: "auth#create", as: "auth" end end end
解决方法
确认路由参数完整性:运行
rails routes查看api/v1/genres的更新路由,确认api_v1_genre_path需要传入Genre的ID,且必须携带更新参数。PUT/PATCH请求缺少参数时,可能导致路由解析失败。补充更新参数:修改测试代码,传入符合命名空间要求的参数结构:
describe "PUT genre" do it "should update genre" do request.headers["Authorization"] = "Token token=#{@token}" genre = Genre.find(1) patch api_v1_genre_path(genre), params: { genre: { name: "Updated Genre" } } expect(response).to have_http_status(:ok) end end
- 区分测试类型:如果使用
patch :update的方式,需确保是控制器测试,并在params中指定:id:
patch :update, params: { id: 1, genre: { name: "Updated Genre" } }
若是请求测试,则必须使用完整的路由辅助方法api_v1_genre_path。
- 验证测试环境路由:在测试中临时添加
puts Rails.application.routes.url_helpers.api_v1_genre_path(1),确认该方法能生成正确URL,排除路由加载问题。
内容的提问来源于stack exchange,提问作者Ale Yanczuk
相关产品推荐
相关产品推荐

