如何对非 restful 端点进行 rspec 控制器测试

how to get rspec controller test to a non-restful endpoint

我正在尝试测试一个不是 rails、(i.e: #index, #new, #edit, #update, #create, #destroy)

中提供的 restful 之一的端点

在我的 routes.rb 文件中:

get 'hospitals/:id/doctors' => 'hospitals#our_doctors'

从我的 hospitals_controller_spec.rb 文件中:

describe "GET #our_doctors" do
  before do
    get :our_doctors
  end
end

但我遇到以下错误:

ActionController::UrlGenerationError: No route matches {:action=>"our_doctors", :controller=>"hospitals"}

我怎样才能让我的规格遵循要求的路线?

我也试过这样称呼它:

get "/hospitals/#{@hospital.id}/doctors" 

但出现以下错误:

ActionController::UrlGenerationError: No route matches {:action=>"/hospitals/1/doctors", :controller=>"hospitals"}

感谢所有帮助,谢谢。

这样命名你的路线如何:

get 'hospitals/:id/doctors' => 'hospitals#our_doctors', as: :our_doctors

如果这不起作用,您可以像这样指定规范使用的路由:

describe "GET #our_doctors" do
  before do
    get :our_doctors, use_route: :our_doctors
  end
end

上述使用 use_route 的解决方案是一个临时解决方案,因为您可能会收到弃用警告(取决于您的 rspec-rails 版本)。以下是我尝试使用该方法时该警告的摘录:

...在功能测试中传递 use_route 选项已被弃用。在 process 方法中支持此选项(以及相关的 getheadpostpatchputdelete helpers) 将在下一个版本中被删除而不进行替换。功能测试本质上是控制器的单元测试,它们不需要知道应用程序的路由是如何配置的。相反,您应该明确地将适当的参数传递给 process 方法...

所以按照建议,为了后代,我会在你的情况下执行以下操作以避免 unsupported/deprecated 语法的任何错误:

get :our_doctors, id: [id_of_hospital]

注意:如果我错了,请纠正我,但以上内容假设您想要呈现特定医院下的所有医生。

一般来说,对于所有非RESTful收集路线测试,我建议如下:

get :action, id: [id_of_resource]

那应该没问题。希望对您有所帮助。