Rspec的:控制器规格为2个嵌套资源(Rspec: Controller specs for 2

2019-09-01 11:32发布

我的routes.rb

  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"}

Answer 1:

你的路线需要至少两个ID:评论的父文章,以及文章的父页。

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

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

所有家长的ID必须为这条路线的工作:

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


Answer 2:

使用Rails 5 PARAMS API改变:

get :index, params: { page_id: @page.id, article_id: @article.id }

https://relishapp.com/rspec/rspec-rails/v/3-7/docs/request-specs/request-spec#specify-managing-a-widget-with-rails-integration-methods



文章来源: Rspec: Controller specs for 2 level nested resources