使用Rspec测试嵌套资源

5

我正在尝试为Rails中的嵌套资源创建测试。 相关的路由定义如下:

resources :communities do
  resources :contents, :type => 'Content'
end

使用RSpec和factory_girl,我正在尝试开始进行例如测试的测试。
describe ContentsController do
  it 'should display a content item under a community' do
    content = FactoryGirl.create(:content)
    get :show, :community_id => content.community.id, :id => content.id
  end
end

这些请求总是会导致结果。
Failure/Error: get :show, :community_id => content.community.id, :id => content.id
 ActionController::RoutingError:
   No route matches {:community_id=>BSON::ObjectId('4e7773c6ac54c3d1ad000002'),
   :id=>BSON::ObjectId('4e7773c6ac54c3d1ad000001'), :controller=>"contents",
   :action=>"show"}

我真的找不到一种方法来使用RSpec指定嵌套资源的路由。我在做什么方面出了根本性的错误吗?

更新:rake routes 的相关部分如下:

    community_contents GET    /communities/:community_id/contents(.:format)             {:action=>"index", :controller=>"contents"}
                       POST   /communities/:community_id/contents(.:format)             {:action=>"create", :controller=>"contents"}
 new_community_content GET    /communities/:community_id/contents/new(.:format)         {:action=>"new", :controller=>"contents"}
edit_community_content GET    /communities/:community_id/contents/:id/edit(.:format)    {:action=>"edit", :controller=>"contents"}
     community_content GET    /communities/:community_id/contents/:id(.:format)         {:action=>"show", :controller=>"contents"}
                       PUT    /communities/:community_id/contents/:id(.:format)         {:action=>"update", :controller=>"contents"}
                       DELETE /communities/:community_id/contents/:id(.:format)         {:action=>"destroy", :controller=>"contents"}

你能发布一下运行 rake routes | grep communities 的结果吗? - corroded
更新原始问题。 - Sami
2
那是一个奇怪的ID。你能展示一下工厂定义中发生了什么吗? - zetetic
请在工厂定义和模型中嵌套资源代码时加上 +1。 - corroded
1个回答

3

我看到您将content.community.id作为:community_id传递,并且该对象看起来像是使用BSON :: ObjectId标识的Mongo文档。请尝试使用以下to_param:

get :show, :community_id => content.community.to_param, :id => content.to_param

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接