Ruby on Rails静态页面GET请求测试触发NameError错误求助
问题排查与解决
问题原因
你的路由配置中通过as: :help、as: :about给路由定义了短别名,同时root 'static_pages#home'对应的路由辅助方法是root_path/root_url,但测试代码错误使用了static_pages_home、static_pages_help_url、static_pages_about_url这类不存在的路由辅助方法,触发了NameError。
从bundle exec rails routes的输出也能验证:
root GET / static_pages#home help GET /help(.:format) static_pages#help about GET /about(.:format) static_pages#about
路由对应的辅助方法名称就是输出最左侧的root、help、about,加上_path或_url后缀即可。
解决方案
方案1:修正测试代码(推荐)
直接使用路由配置对应的正确辅助方法,修改test/controllers/static_pages_controller_test.rb:
require "test_helper" class StaticPagesControllerTest < ActionDispatch::IntegrationTest test "should get home" do get root_path # 替换static_pages_home assert_response :success assert_select "title", "Ruby on Rails Tutorial Sample App" end test "should get help" do get help_path # 替换static_pages_help_url assert_response :success assert_select "title", "Ruby on Rails Tutorial Sample App" end test "should get about" do get about_path # 替换static_pages_about_url assert_response :success assert_select "title", "Ruby on Rails Tutorial Sample App" end end
注:_path生成相对路径,_url生成完整URL,集成测试中两者均可正常使用。
方案2:修改路由配置(适配原有测试代码)
如果想保留static_pages_xxx_url这类命名的辅助方法,调整config/routes.rb,给路由指定对应别名:
Rails.application.routes.draw do resources :microposts resources :users # 给root路由指定别名 get '/', to: 'static_pages#home', as: :static_pages_home # 给help和about路由指定完整别名 match '/help', to: 'static_pages#help', via: 'get', as: :static_pages_help match '/about', to: 'static_pages#about', via: 'get', as: :static_pages_about end
修改后重新运行bundle exec rails routes,就能看到对应的路由辅助方法,原有测试代码无需修改即可运行。
验证
修改完成后,重新执行测试命令:
rails test
所有测试应该可正常通过。
内容的提问来源于stack exchange,提问作者JS3
相关产品推荐
相关产品推荐

