【问题标题】:Rails 4 -No route matches, route is defined. Only occurs in testingRails 4 - 没有路线匹配,路线已定义。只发生在测试中
【发布时间】:2016-07-03 16:50:49
【问题描述】:

所以我正在关注 Michael Hartl 的 Rails 教程,我正在学习第 5 章 (https://www.railstutorial.org/book/filling_in_the_layout)。

当我运行他为注册链接添加的最终测试时:

class UsersControllerTest < ActionDispatch::IntegrationTest

  test "should get new" do
    get signup_path
    assert_response :success
  end
end

我在运行测试时收到此错误:

ERROR["test_should_get_new", UsersControllerTest, 2016-07-01 17:48:25 +0100]
 test_should_get_new#UsersControllerTest (1467391705.83s)
ActionController::UrlGenerationError:         ActionController::UrlGenerationError: No route matches {:action=>"/signup", :controller=>"users"}
            test/controllers/users_controller_test.rb:6:in `block in <class:UsersControllerTest>'
        test/controllers/users_controller_test.rb:6:in `block in <class:UsersControllerTest>'

这里是路由文件:

Rails.application.routes.draw do

  root 'static_pages#home'
  get '/signup', to: 'users#new'
  get '/help', to: 'static_pages#help'
  get '/about', to: 'static_pages#about'
  get '/contact', to: 'static_pages#contact'

end

我在视图中使用了 signup_path 助手作为链接,它们工作正常。

当我在路由中定义“signup”应该成为用户控制器中的新操作时,为什么 test 会尝试访问名为“/signup”的操作?

【问题讨论】:

    标签: ruby-on-rails testing path get routes


    【解决方案1】:

    因为它是一个控制器测试(而不是功能测试),你的控制器不应该关心你访问了哪个 url。因此,get 需要一个动作,而不是路径。

    改变

    get signup_path
    

    到

    get :new
    

    【讨论】:

      【解决方案2】:

      如果你想测试路由,你可以将你的测试用例修改为以下。

      1. assert_generates 断言特定选项生成特定路径。 assert_generates '/signup', {controller: 'users', action: 'new'}

      1. assert_recognizes 是 assert_generates 的反面。它断言给定路径已被识别并将其路由到应用程序中的特定位置。

        assert_recognizes({ controller: 'users', action: 'new'}, '/signup')


      1. assert_routing 断言以两种方式检查路由:它测试路径是否生成选项,以及选项是否生成路径。因此,它结合了assert_generates和assert_recognizes的功能。

        assert_routing({ path: 'signup', method: :get }, { controller: 'users', action: 'new' })

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-07-16
        • 2012-10-11
        • 2017-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多