我有这条路由:

Rails.application.routes.draw do
  get "my_profile", to: "users#show"
end

它创建了这条路由:

my_profile GET    /my_profile(.:format)   users#show

我可以很容易地在UsersControllerTest中测试users#show操作,但我想测试自定义路由是否存在,并在操作上执行代码.比如:

class UsersControllerTest < ActionController::TestCase
  def test_my_profile_route
    get "/my_profile"
    # Testing stuff
  end
end

但我得到:

ActionController::UrlGenerationError: No route matches {:action=>"/my_profile", :controller=>"users"}

推荐答案

测试该路由与测试Rails中的任何其他路由没有什么不同.

相反,这里的问题是你使用的是旧的deprechiated controller tests (ActionController::ControllerTest)而不是integration test (ActionDispatch::IntegrationTest).

控制器测试表面上相似,但本质上不同.而不是真正的HTTP请求,get方法直接将操作分派到控制器的实例上,该实例被馈送到一个假请求.因此,它与对应于实际方法名称的符号一起使用.众所周知,这个过程存在极大的缺陷,而且控制器测试长期以来一直只局限于遗留应用程序.

def test_my_profile_route
  get :my_profile
end

错误No route matches {:action=>"/my_profile", :controller=>"users"}是因为Controller::ControllerTest试图通过使用控制器和操作名称查找路由来验证路由是否存在.注意正斜杠.

将测试的超类更改为ActionDispatch::IntegrationTest,并确保使用的是最新的教程/指南.

class UserProfileFlowsTest < ActionDispatch::IntegrationTest
  test "can see the users profile" do
    # @todo sign in the user
    get "/my_profile"
    assert_select "h1", "Users#my_profile"
  end
end

Ruby-on-rails相关问答推荐

如何在_serialize之前执行代码?""或者如何在序列化属性之前对属性进行清理?

为Rails服务器推荐的交付类型

多对多模型通过控制台创建记录不起作用

将参数传递给视图中的嵌入操作时遇到问题

错误:部署到 Heroku 时找不到模块tailwindcss/defaultTheme

Rails:当 id 方法为非标准时构建关联

Rails 7.0.4 和 link_to 的数据确认不起作用

如何获取 Rails 表单构建器将为某个字段生成的 HTML名称属性?

如何避免 has_many :through 关系中的重复?

Ruby on Rails 中的消息队列

是否可以在 Rails 中否定范围?

如何在 Rails 应用程序中使用长 id?

如何在 Ruby 中创建一个新的 Date 实例

我可以将默认值传递给 rails 生成迁移吗?

rmagick 和 OS X Lion

对象不支持此属性或方法 Rails Windows 64bit

在 Rails 应用程序中处理大文件上传的最佳方法是什么?

Rails Associations - has_many => :through - 但相同的模型

Rails HABTM - 正确删除关联

设计:为什么我的注销链接不起作用?