【问题标题】:Problem with routes in functional testing功能测试中的路由问题
【发布时间】:2011-01-06 13:20:42
【问题描述】:

我正在制作一个简单的测试项目来为我的测试做准备。 我对嵌套资源相当陌生,在我的示例中,我有一个 newsitem,每个 newsitem 都有 cmets。

路由看起来像这样:

resources :comments

resources :newsitems do
    resources :comments
end

我现在正在为 cmets 设置功能测试,但遇到了一些问题。

这将获得新闻站点的 cmets 的索引。 @newsitem 在设置 ofc 中声明。

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

我不能使用名称路径或我在这里做错了什么吗?

提前致谢。

【问题讨论】:

    标签: ruby-on-rails resources nested functional-testing nested-resources


    【解决方案1】:

    问题在于您的测试指定 URL 的方式。错误信息是:

    No route matches {:controller=>"comments", :action=>"/newsitems/1/comments/new"}
    

    当然没有名为“/newsitems/1/cmets/new”的操作。你想传递哈希{ :controller => :comments, :action => :new, :news_item_id => 1 }

    正确的语法很简单:

    get :new, :news_item_id => 1
    

    【讨论】:

    • 我在有许多嵌套路由的功能测试中遇到了类似的问题。这帮助很大!谢谢@zetetic
    【解决方案2】:

    (假设 Rails 3)

    在您的 routes.rb 中试试这个

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

    【讨论】:

    • 还是一样的问题。我现在使用 get :index,{:controller => "/cmets",:newsitem_id => @newsitem} 并且它不返回任何错误。但这只会让我到达 host:port/cmets/new 对吗?但这应该不是问题,因为我给了newsitem,对吗?只是觉得很奇怪为什么我不能使用路径:s
    • 鉴于您实际上在routes.rb 中指定了嵌套资源,我认为您应该完全删除该行。 Rails 应该已经为您设置了一个命名路径。检查rake routes 的输出,但它应该类似于new_newsitem_comment
    猜你喜欢
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    相关资源
    最近更新 更多