Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
898 views
in Technique[技术] by (71.8m points)

ruby on rails - Rspec: Controller specs for 2 level nested resources

my routes.rb

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

While writing controller specs for Comments:

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 

Any idea how to give the page and article reference to get :index ?? if I give : get :index, :article_id => @article.id
Error I get is below:

 Failure/Error: get :index, :article_id => @article.id
 ActionController::RoutingError:
   No route matches {:article_id =>"3", :controller=>"magazine/comments"}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your route requires at least two IDs: the comment's parent article, and the article's parent page.

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

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

All parent IDs must be provided for this route to work:

it "renders the :index view" do
  get :index, {:page_id => @page.id, :article_id => @article.id}
  # [UPDATE] As of Rails 5, this becomes:
  # get :index, params: {:page_id => @page.id, :article_id => @article.id}
  response.should render_template("index")
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...