Rails教程静态页面路由测试红(5.28)

Rails Tutorial static pages routes test red (5.28)

正在执行 Michael Hartl 的 Rails 教程,但在清单 5.28 上遇到困难(进行红色测试而不是绿色测试),更改测试以匹配新路由。

所有页面(/、/about、/contact、/help)的错误:

ActionController::UrlGenerationError: No route matches {:action=>"/*", :controller=>"static_pages"}

routes.rb

Rails.application.routes.draw do
  root 'static_pages#home'
  get  '/help',    to: 'static_pages#help'
  get  '/about',   to: 'static_pages#about'
  get  '/contact', to: 'static_pages#contact'
end

tests/controllers/static_pages_controller_test.rb

require 'test_helper'

class StaticPagesControllerTest < ActionController::TestCase
  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

static_pages_controller.rb

class StaticPagesController < ApplicationController
  def home
  end

  def help
  end

  def about
  end

  def contact
  end

end

如果您需要查看任何其他代码,请告诉我!尝试在每次获取路线后添加 as: '*',但无济于事。

不确定这是否是 ruby/rails 版本问题,但我在 IDE 上使用 Rails 4.2.2 和 Ruby 2.3.0,但是 "rails test"(按照 Hartl 的指示使用)将不起作用(反击 "test Command not found")。不确定这是对更大问题还是不相关的暗示。提前致谢!

编辑:使用这些路径的链接(如下所示)呈现正确,只是测试失败。

<%= link_to "Home",   root_path %>
<%= link_to "Help",   help_path %>

您的 test/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

按照我的建议更改上面的文件,运行 $ rails test 你可以看到绿色测试。我还建议您将您的应用程序升级到 rails 5.0.0,因为 Michael Hartl 已经将他的 rails tutorials 升级到 rails 5.0.0,将来您有更多的东西要学,如果您升级它,您的学习之旅将更加无误和愉快。