2013-07-15 95 views
1

構建我的應用時,我生成了腳手架,它創建了標準的Rspec測試。我想利用這些試驗的覆蓋範圍,但他們似乎沒有因嵌套的路線:調整嵌套路由的rspec路由測試

當我運行測試,這是它的反饋:

Failures: 

    1) ListItemsController routing routes to #index 
    Failure/Error: get("/list_items").should route_to("list_items#index") 
     No route matches "/list_items" 
    # ./spec/routing/list_items_routing_spec.rb:7:in `block (3 levels) in <top (required)>' 

Finished in 0.25616 seconds 
1 example, 1 failure 

我怎麼告訴Rspec的那有嵌套的路線?

這裏有刪節文件:

list_items_routing_spec.rb:

require "spec_helper" 

describe ListItemsController do 
    describe "routing" do 

    it "routes to #index" do 
     get("/list_items").should route_to("list_items#index") 
    end 

end 

list_items_controller_spec.rb:

describe ListItemsController do 
    # This should return the minimal set of attributes required to create a valid 
    # ListItem. As you add validations to ListItem, be sure to 
    # adjust the attributes here as well. 
    let(:valid_attributes) { { "list_id" => "1", "project_id" => "1" } } 

    # This should return the minimal set of values that should be in the session 
    # in order to pass any filters (e.g. authentication) defined in 
    # ListItemsController. Be sure to keep this updated too. 
    let(:valid_session) { {} } 

    describe "GET index" do 
    it "assigns all list_items as @list_items" do 
     list_item = ListItem.create! valid_attributes 
     get :index, project_id: 2, {}, valid_session 
     assigns(:list_items).should eq([list_item]) 
    end 
    end 

的routes.rb:

resources :projects do 
    member do 
     match "list_items" 
    end 
    end 

注: - 我試過改變rpec測試自己來包含一個project_id,並沒有幫助。 - 我使用工廠女生夾具生成(不知道這是否相關)

感謝您的幫助!

回答

2

首先,運行rake routes來查看存在哪些路由。

根據你的路線,我希望你有一個ProjectsController有一個行動list_items。此行動將在/projects/:id/list_items下提供。

現在我只能推理你想要什麼,但我會猜測。

如果你想/projects/:project_id/list_items路由到list_items#index你有你的路線更改爲:

resources :projects do 
    resources :list_items 
end 

您可以通過運行rake routes確認。

然後修復斷言在你的路由規格:

get("/projects/23/list_items").should route_to("list_items#index", :project_id => "23") 

更新RSpec的v2.14 +期望

expect(:get => "/projects/23/list_items").to route_to("list_items#index", :project_id => "23") 
+0

戴夫嗨,我想我一定要有 「成員做」在我的路由文件中,以正確嵌套和訪問這些文件(否則我得到路由失敗)。有沒有辦法將此會員關係轉告給Rspec?目前,當我運行你給我的斷言時,它失敗了:失敗/錯誤:get(「/ projects/23/list_items」)。route_to(「list_items#index」,:project_id =>「23」) 選項<{"action"=>「index」,「controller」=>「list_items」,「id」=>「23」}>不匹配<{「project_id」=>「23」,「controller」=>「list_items」,「action 「=>」index「}>,區別:<{」project_id「=>」23「,」id「=>」23「}>。 –

+0

看。這是你的代碼。做一定你想要的。通過成員路由,路由器會將請求路由到'projects#list_items',這不是我想要的。有關路由如何工作以及如何嵌套資源,請參閱Rails指南:http://guides.rubyonrails.org/routing。html#nested-resources – DaveTsunami

+1

我剛剛注意到,表示id的數字必須是字符串格式。在我的情況下,@ director.id.to_s – schwabsauce