Ruby on rails Rspec:2级嵌套资源的控制器规格
我的路线.rbRuby on rails Rspec:2级嵌套资源的控制器规格,ruby-on-rails,rspec,controller,Ruby On Rails,Rspec,Controller,我的路线.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 = F
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
你知道如何提供页面和文章参考以获取:索引吗??
如果我给出:get:index,:article\u id=>@article.id我得到的错误如下:
Failure/Error: get :index, :article_id => @article.id
ActionController::RoutingError:
No route matches {:article_id =>"3", :controller=>"magazine/comments"}
您的路由至少需要两个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}
# [UPDATE] As of Rails 5, this becomes:
# get :index, params: {:page_id => @page.id, :article_id => @article.id}
response.should render_template("index")
end
在Rails 5中,参数API发生了变化:
get :index, params: { page_id: @page.id, article_id: @article.id }
因此,如果我想测试一个负面情况-请求中没有页面id-那么我该怎么做?这将导致路由错误。Rails指南说“资源应该”。它不会导致错误。事实上,正如你们所看到的:Rails指南说你们不应该这样做,并不是说你们不能这样做。@BartlomiejSkwira这是不可能的。除非Rails路由器中有bug。