RSpec测试Rails时post_categories_url返回错误路径如何解决
问题原因
- 路由参数匹配顺序错误:你的路由配置中scope层级第一个动态参数是可选的
:locale,当你给路由辅助方法传参时,Rails会优先将第一个未命名参数匹配路由中最靠前的动态参数。你传入的post_category对象的id值2被识别为locale参数的值,所以路径前缀会出现/2/。 - 路由辅助方法名称错误:
resources :post_categories生成的单个资源详情页(show动作)的路由辅助方法是单数形式post_category_url,你用的复数post_categories_url对应的是列表页(index动作),本身不需要传入资源id参数,错误的方法名进一步导致参数匹配逻辑异常。
修复方案
你可以根据业务场景选择以下任意一种组合方案:
- 首先修正路由辅助方法名称,使用单数形式的
post_category_url调用单个分类的show路径 - 处理locale参数匹配问题,可从三个维度解决:
- 调用路由辅助方法时主动传入locale参数
- 在路由scope配置中添加locale默认值
- 在应用控制器中配置全局默认url_options,自动携带locale参数
修正后的测试代码示例:
describe "GET /show" do it "renders a successful response" do post_category = PostCategory.create! valid_attributes # 修正为单数路由方法,主动传入locale puts post_category_url(post_category, locale: I18n.locale) get post_category_url(post_category, locale: I18n.locale) expect(response).to be_successful end end
如果希望避免每次调用路由方法都传locale,可修改路由配置添加默认值:
scope "(:locale)", locale: /en|ru/, defaults: { locale: 'en' } do # 原有路由配置保持不变 get '/user/:id' => 'users#show', as: 'user' get '/users' => 'users#index' resources :post_categories, path: 'categories' resources :posts, path: 'adv' end
也可以在app/controllers/application_controller.rb中配置全局默认参数:
def default_url_options { locale: I18n.locale } end
内容的提问来源于stack exchange,提问作者Vasil Laurynovich
相关产品推荐
相关产品推荐

