Rspec:2级嵌套资源的控制器规范

Oat*_*eal 22 controller rspec ruby-on-rails

我的routes.rb

  namespace :magazine do
   resources :pages do
     resources :articles do
       resources :comments
     end
   end
  end
Run Code Online (Sandbox Code Playgroud)

在为评论编写控制器规范时:

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 
Run Code Online (Sandbox Code Playgroud)

任何想法如何给页面和文章引用get:index ?? 如果我给:get:index,:article_id => @ article.id
我得到的错误如下:

 Failure/Error: get :index, :article_id => @article.id
 ActionController::RoutingError:
   No route matches {:article_id =>"3", :controller=>"magazine/comments"}
Run Code Online (Sandbox Code Playgroud)

Sub*_*ial 41

您的路线至少需要两个ID:评论的父文章和文章的父页面.

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

# => /magazine/pages/:page_id/articles/:article_id/comments
Run Code Online (Sandbox Code Playgroud)

必须提供所有父ID才能使此路由生效:

it "renders the :index view" do
  get :index, {:page_id => @page.id, :article_id => @article.id}
  response.should render_template("index")
end
Run Code Online (Sandbox Code Playgroud)

  • @gg_s它不会导致错误.事实上你可以看到:http://guides.rubyonrails.org/routing.html#limits-to-nesting Rails指南说你*应该*不要这样做,而不是你做不到. (3认同)