2

我正在做一个简单的测试项目,为我的测试做好准备。 我对嵌套资源相当陌生,在我的例子中,我有一个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

(假设Rails 3中)

试试这个在您的routes.rb

GET 'newsitems/:newsitem_id/comments/new(.:format)' => 'comments#new', :as => :new_newsitem_comment 
+0

还是一样problemen。 我使用的是 get:index,{:controller =>“/ comments”,:newsitem_id => @newsitem} 现在它不返回任何错误。但这只会让我到主机:端口/评论/新的权利?但是,这不应该成为一个问题,因为我给它的新网站正确吗? 只是发现它很奇怪,为什么我不能使用路径:s – Wishmaster 2011-01-06 14:12:39

+0

鉴于你实际上指定`routes.rb`中的嵌套资源,我认为你应该完全删除该行。 Rails应该为你建立一条命名路径。检查`rake routes`的输出,但它应该是`new_newsitem_comment`类似的东西 – 2011-01-06 14:38:31

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