如何使用rspec测试带有嵌套路由的控制器

16

我使用InheritedResource创建了控制器。

class AppsController < InheritedResources::Base
  belongs_to :company

  # Devise
  before_filter :login_or_oauth_required
  # CanCan
  load_and_authorize_resource
end

通过这种方法尝试使用 Rspec 进行测试

require "spec_helper"

include Devise::TestHelpers

describe AppsController do
  before(:each) do
    @company_1 = Factory.build(:company)
    application_1 = Factory.create(:application, :company => @company_1)
    application_2 = Factory.create(:application, :company => @company_1)
    application_3  = Factory.create(:application, :company => @company_1)    
    @company_2 = Factory.build(:company)

    @user_1   = Factory.create(:user)
    role_1    = Factory.create(:publisher_role, :company => @company_1) 
    profile_1 = Factory.create(:profile, :company => @company_1, :user => @user_1, :roles => [role_1])
  end

  describe "index action" do
    it "user_1 should have 3 applications from company_1" do
      sign_in @user_1
      params = {"company_id"=>"1"}
      get :index
      assigns[:apps].should have(3).items
    end
  end
end
结果是
Failure/Error: get :index
     ActionController::RoutingError:
       No route matches {:controller=>"apps"}
如何告诉Rspec进入我的嵌套路由?
我的路由:
  resources :companies do
    resources :apps do
      resources :shelves do
        resources :publications
      end
    end
  end

我试图遵循这个问题:如何使用Rspec测试嵌套路由控制器?,但它在我的情况下无法工作。

我使用的是Rails 3.1.1和rspac 2.7。


2
就此而言,Rails指南不鼓励超过一层的嵌套资源。"资源嵌套不应超过1层深" (http://guides.rubyonrails.org/routing.html#nested-resources),并将读者引用至这个[怪物](http://weblog.jamisbuck.org/2007/2/5/nesting-resources)。但是你得做你该做的事情。 - brntsllvn
1个回答

48

我找到了解决方案 :-P

我的做法只是改变了以下内容:

get :index
抱歉,根据要求我无法回答这个问题。
get :index, :company_id => @company_1.id

6
在新的 RSpec 语法中,可以这样写:get :index, params: { company_id: @company_1.id } - Oleg Afanasyev

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