是否应该有任何嵌套路由的直接资源路由?

时间:2015-01-27 03:10:19

标签: ruby-on-rails rspec rails-api

我有一个用户类和一个类Task。我的任务资源路径嵌套在用户资源中,任务属于用户和用户has_many任务。

resources :users, except: [:new, :edit] do
  resources :tasks, except: [:new, :edit] 
end

在我的rspec"请求"测试我正在尝试使用关联用户发布新任务,但看起来它最终尝试点击它找不到的直接/tasks路由。如果我的路径文件如下所示,则测试通过:

  resources :users, except: [:new, :edit] do
    resources :tasks, except: [:new, :edit] 
  end

  resources :tasks, except: [:new, :edit] 

测试看起来像这样(有before(:each)创建@user1):

  describe "POST /users/1/tasks" do
    it "creates a new task for user1" do
        post user_tasks_path(@user1, task: {description: "post new task", due_date: "2/1/15", user_id: @user1.id})
        expect(response).to have_http_status(201)
        puts response.body
    end
  end

1 个答案:

答案 0 :(得分:2)

不,没有必要为嵌套的资源提供直接资源。

现在,关于你的规格。我不确定它是否尝试覆盖/tasks,但请注意post方法的语法:

post(action, *args)

那就是说,你应该这样做:

post(user_tasks_path(@user1), task: {})

而不是:

post(user_tasks_path(@user1, task: {}))

HTH。