【问题标题】:how to get rspec controller test to a non-restful endpoint如何让 rspec 控制器测试到非静态端点
【发布时间】:2015-08-23 17:32:38
【问题描述】:

我正在尝试测试一个不是 rails 中提供的 restfuls 之一的端点,(i.e: #index, #new, #edit, #update, #create, #destroy)

在我的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"}

感谢所有帮助,谢谢。

【问题讨论】:

    标签: ruby-on-rails rspec routing


    【解决方案1】:

    这样命名你的路线怎么样:

    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
    

    【讨论】:

    • 哦,谢谢,get 'hospitals/:id/doctors' => 'hospitals#our_doctors', as: :our_doctors 工作。你能解释一下下面的另一个吗? (get :our_doctors, use_route: :our_doctors) 谢谢。
    • 没有问题。是的,如果您的控制器规范无法自动找到您的请求(获取:our_doctors),您可以使用 use_route 给它一个提示
    【解决方案2】:

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

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

    因此,按照建议,为了后代,我会在您的情况下执行以下操作以避免不支持/不推荐使用的语法出现任何错误:

    get :our_doctors, id: [id_of_hospital]
    

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

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

    get :action, id: [id_of_resource]
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多