使用RSpec测试嵌套资源

时间:2011-09-19 16:56:25

标签: ruby-on-rails factory-bot rspec-rails nested-resources

我正在尝试在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指定到嵌套资源的路径的方法。我在这里做了一些根本错误的事情吗?

更新:佣金路线的相关部分是:

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

1 个答案:

答案 0 :(得分:3)

我看到您将content.community.id作为:community_id传递,该对象看起来像是一个用BSON :: ObjectId标识的mongo文档。尝试使用to_param,如下所示:

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