我正在使用railstutorial.org上的Michael Hartl教程。我遇到了困难在第5章中,让路由工作。 如果我从路线文件开始
routes.rb
Rails.application.routes.draw do
root 'static_pages#home'
get 'static_pages/help'
get 'static_pages/about'
get 'static_pages/contact'
对于每一个都有像
这样的测试static_pages_controller_test.rb
test "should get home" do
get :home
assert_response :success
assert_select "title", "Ruby on Rails Tutorial Sample App"
end
这种语法有效并且所有测试都通过但后来他想使用* _path约定更改语法。
所以现在测试看起来像
class StaticPagesControllerTest < ActionController::TestCase
test "should get home" do
get root_path
.
.
end
test "should get help" do
get help_path
.
.
end
我将路线更新为
root 'static_pages#home'
get '/help', to: 'static_pages#help'
get '/about', to: 'static_pages#about'
get '/contact', to: 'static_pages#contact'
但现在所有的测试都失败了消息
ERROR["test_should_get_home", StaticPagesControllerTest, 2016-06-30 05:02:41 -0700]
test_should_get_home#StaticPagesControllerTest (1467288161.43s)
ActionController::UrlGenerationError: ActionController::UrlGenerationError:
No route matches {:action=>"/", :controller=>"static_pages"}
ERROR["test_should_get_help", StaticPagesControllerTest, 2016-06-30 05:02:41 -0700]
test_should_get_help#StaticPagesControllerTest (1467288161.43s)
ActionController::UrlGenerationError: ActionController::UrlGenerationError:
No route matches {:action=>"/help", :controller=>"static_pages"}
我的控制器看起来像这样
class StaticPagesController < ApplicationController
def home
end
def help
end
.
.
end
如果我运行rake路线,我会
Prefix Verb URI Pattern Controller#Action
root GET / static_pages#home
help GET /help(.:format) static_pages#help
about GET /about(.:format) static_pages#about
contact GET /contact(.:format) static_pages#contact
我做错了什么?
答案 0 :(得分:1)
您需要重写这些路线,以便根据您的测试为您创建动态路线助手。写得像,
get 'static_pages/help' , as: :help
get 'static_pages/about' , as: :about
get 'static_pages/contact' , as: :contact
根据您当前的路线,这些*_path
会像static_pages_about
,static_pages_help
等。我不知道您是如何获得rake routes
输出的不使用as
选项。
答案 1 :(得分:0)
是作者上周用5.0.0更新了rails教程。建议你更新它,这将使更进一步的旅程更愉快和没有错误,你将获得更多的新东西要学习5.0.0
更新 tests / controllers / static_pages_controller_test.rb
require 'test_helper'
class StaticPagesControllerTest < ActionDispatch::IntegrationTest
test "should get home" do
get root_path
assert_response :success
assert_select "title", "Ruby on Rails Tutorial Sample App"
end
test "should get help" do
get help_path
assert_response :success
assert_select "title", "Help | Ruby on Rails Tutorial Sample App"
end
test "should get about" do
get about_path
assert_response :success
assert_select "title", "About | Ruby on Rails Tutorial Sample App"
end
test "should get contact" do
get contact_path
assert_response :success
assert_select "title", "Contact | Ruby on Rails Tutorial Sample App"
end
end
我相信一旦你更新 tests / controllers / static_pages_controller_test.rb ,你会看到绿色测试$ rails test
答案 2 :(得分:-1)
我不太确定,但如果你这样做会发生什么:
root 'static_pages#home'
get 'help', to: 'static_pages#help'
get 'about', to: 'static_pages#about'
get 'contact', to: 'static_pages#contact'