我正在做一个简单的测试项目,为我的测试做好准备。 我对嵌套资源很新,在我的例子中我有一个newsitem,每个newsitem都有注释。
路由如下所示:
resources :comments
resources :newsitems do
resources :comments
end
我正在为评论设置功能测试,但我遇到了一些问题。
这将获得newsitem的评论索引。 @newsitem在c的设置中声明。
test "should get index" do
get :index,:newsitem_id => @newsitem
assert_response :success
assert_not_nil assigns(:newsitem)
end
但问题出在这里,“应该变得新”。
test "should get new" do
get new_newsitem_comment_path(@newsitem)
assert_response :success
end
我收到以下错误。
ActionController::RoutingError: No route matches {:controller=>"comments", :action=>"/newsitems/1/comments/new"}
但是当我查看路线表时,我看到了:
new_newsitem_comment GET /newsitems/:newsitem_id/comments/new(.:format) {:action=>"new", :controller=>"comments"}
我不能使用名称路径或我在这里做错了吗?
提前致谢。
答案 0 :(得分:7)
问题在于您的测试指定URL的方式。错误消息是:
No route matches {:controller=>"comments", :action=>"/newsitems/1/comments/new"}
当然没有名为“/ newsitems / 1 / comments / new”的动作。您想要传递哈希{ :controller => :comments, :action => :new, :news_item_id => 1 }
。
正确的语法很简单:
get :new, :news_item_id => 1
答案 1 :(得分:0)
(假设Rails 3)
在routes.rb
GET 'newsitems/:newsitem_id/comments/new(.:format)' => 'comments#new', :as => :new_newsitem_comment