2013-04-30 170 views
17

我的routes.rbRspec的:控制器的規格爲2級嵌套資源

namespace :magazine do 
    resources :pages do 
    resources :articles do 
     resources :comments 
    end 
    end 
    end 

在寫控制器規格註釋:

describe "GET 'index'" do 
    before(:each) do 
    @user = FactoryGirl.create(:user) 
    @page = FactoryGirl.build(:page) 
    @page.creator = @user 
    @page.save 
    @article = FactoryGirl.create(:article) 
    @comment_attributes = FactoryGirl.attributes_for(:comment, :article_id => @article) 
    end 
it "populates an array of materials" do 
    get :index, ?? 
    #response.should be_success 
    assigns(:comments) 
end 

it "renders the :index view" do 
    get :index, ?? 
    response.should render_template("index") 
end 

end 

任何想法如何給網頁和文章引用來獲得:索引? 如果我給:得到:指數:article_id的=> @ article.id
錯誤我得到的是如下:

Failure/Error: get :index, :article_id => @article.id 
ActionController::RoutingError: 
    No route matches {:article_id =>"3", :controller=>"magazine/comments"} 

回答

33

你的路線需要至少兩個ID:評論的父文章,以及文章的父頁。

namespace :magazine do 
    resources :pages do 
    resources :articles do 
     resources :comments 
    end 
    end 
end 

# => /magazine/pages/:page_id/articles/:article_id/comments 

標識必須爲這條線路提供所有家長的工作:

it "renders the :index view" do 
    get :index, {:page_id => @page.id, :article_id => @article.id} 
    response.should render_template("index") 
end 
+1

這工作謝謝:) – Oatmeal 2013-04-30 10:43:53

+0

所以,如果我想測試一個不利的局面 - PAGE_ID是不是在要求 - 那我該怎麼做? – 2014-02-02 17:03:17

+0

這將導致路由錯誤。 Rails指南說:「資源應該[永遠不會嵌套超過1層](http://guides.rubyonrails.org/routing.html#nested-resources)。」 – Substantial 2014-02-04 21:29:42