无法测试嵌套 Rails 控制器

Unable to test nested Rails controller

我如何设法测试 Task::HoursController? 来自我的 rspec 测试的请求命中 HoursController,而不是 Task::HoursController

路线

# POST /tasks/:task_id/hours(.:format) tasks/hours#create

测试

describe Tasks::HoursController, :type => :controller do

  it "assigns all hours as @hours" do
      hour = Hour.create! valid_attributes
      get  :index, { task_id:  @task.id }, valid_session
      assigns(:hours).should eq([hour])
  end
end

日志输出

Processing by HoursController#index as HTML
  Parameters: {"task_id"=>"207"}
Completed 500 Internal Server Error in 3ms

我想您需要删除 Tasks 命名空间(另请注意,在您的描述中使用单数,而在代码中使用复数)

并将描述块放入具有任务命名空间的模块中。

module Tasks
  describe HoursController do
    it "assigns all hours as @hours" do
        hour = Hour.create! valid_attributes
        get  :index, { task_id:  @task.id }, valid_session
        assigns(:hours).should eq([hour])
    end
  end
end

你们很难看到,因为我没有post我的控制器的代码。

修复是这样的:

-class Tasks::HoursSpentController < ApplicationController
+module Tasks
+  class HoursSpentsController < ApplicationController

以及建议@vince-v posted。 谢谢文斯。 :-)