带有嵌套资源的RSpec路由错误

时间:2017-05-24 20:34:11

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

我有一个我认为应该毫无问题地通过的规范,但我相信,因为它是一个嵌套资源,它可能会抛弃我的请求。我正在使用Rails 4.2和Ruby 2.3.3。这是怎么回事?我知道这是一条有效的路线,因为当我点击rake routes

时出现

的routes.rb

    scope '/organizations/:organization_id' do
      get 'dashboard', to: 'projects#dashboard'
      resources :projects, except: [:delete] do
        get 'configure', to: 'projects#configure'
        post 'configure', to: 'projects#configure'
        get 'team', to: 'projects#team'
        get 'subprojects', to: 'projects#subprojects'
        collection do
          get 'search', to: 'projects#search'
          get 'find', to: 'projects#find'
          post 'create_by_sf_id', to: 'projects#create_by_sf_id'
        end
        resources :courses do
          get 'module_progress', to: 'courses#module_progress'
          get 'add_content', to: 'courses#add_content'
          get 'summary', to: 'courses#summary'
          post 'summary', to: 'courses#summary'
        end
        resources :tasks
      end
    end

projects_controller_spec.rb

describe 'GET project_team' do
  it 'should render the project team page' do
    get :team, organization_id: organization.id, id: project.id
    expect(response.code).to eq '200'
  end
end

projects_controller.rb

def team
  @team = @project.project_team
end

... Aaaand产生的错误:

1) ProjectsController when authenticating as a customer GET project_team should render the project team page
 Failure/Error: get :team, organization_id: organization.id, id: project.id

 ActionController::UrlGenerationError:
   No route matches {:action=>"team", :controller=>"projects", :id=>"460", :organization_id=>"417"}
 # ./spec/controllers/projects_controller_spec.rb:90:in `block (4 levels) in <top (required)>'

1 个答案:

答案 0 :(得分:0)

team嵌套在projects下,它会给你:

project_team GET  /organizations/:organization_id/projects/:project_id/team(.:format)  projects#team

所以这个:

get :team, organization_id: organization.id, id: project.id

应该是这样的:

get :team, organization_id: organization.id, project_id: project.id

看起来你可能会遇到麻烦:

def team
  @team = @project.project_team
end

因为您不会查找@project(除非您在before_action挂钩中执行此操作)。

最后,我很想创建一个ProjectTeamController。这样,您可以使用show方法而不是非标准team方法。但是,这是个人偏好的问题。