在Rails 3.1中使用rspec测试嵌套资源控制器

时间:2011-12-13 21:55:13

标签: ruby-on-rails rspec controller ruby-on-rails-3.1 routes

我正在尝试为嵌套资源的控制器进行测试。

在routes.rb

中嵌套是这样的
resources :cars, :only => [:index, :destroy, :show] do
  resources :car_subscriptions, :only => [:new, :create], :as => :follow_subscriptions
end

我正在尝试最具体地测试创建操作:

describe CarSubscriptionsController do

  def valid_attributes
    {:car_id => '1', :user_id => '2'}
  end

  describe "POST create" do
    describe "with valid params" do
      it "creates a new CarSubscription" do
        expect {
          post :create, :car_id => 1, :car_subscription => valid_attributes
        }.to change(CarSubscription, :count).by(1)
      end

      it "assigns a newly created car_subscription as @car_subscription" do
        post :create, :car_subscription => valid_attributes
        assigns(:car_subscription).should be_a(CarSubscription)
        assigns(:car_subscription).should be_persisted
      end

      it "redirects to the created car_subscription" do
        post :create, :car_subscription => valid_attributes
        response.should redirect_to(CarSubscription.last)
      end
    end
  end

end

它实际上是rails脚本生成的脚手架的一部分。我只修改了第一个'it'

中的valid_attributes和post

输出是这样的:

  1) CarSubscriptionsController POST create with valid params creates a new CarSubscription
     Failure/Error: post :create, :car_id => 1, :car_subscription => valid_attributes
     ActionController::RoutingError:
       No route matches {:car_id=>"1", :car_subscription=>{:car_id=>"1", :user_id=>"2"}, :controller=>"car_subscriptions", :action=>"create"}
     # ./spec/controllers/car_subscriptions_controller_spec.rb:34:in `block (5 levels) in <top (required)>'
     # ./spec/controllers/car_subscriptions_controller_spec.rb:33:in `block (4 levels) in <top (required)>'

所有'它都是同样的错误。

我已尝试从routes.rb文件中删除:as => :following_subscriptions,但同样的问题。

我实际上已经拆分了car_subscriptions的资源,因此indexdestroy没有嵌套,createnew嵌套在:cars < / p>

我不想使用像answer这样的硬编码路径,但如果这是唯一的方法,我可以尝试一下:

{ :post => "/forum_topics/1/forum_sub_topics" }.should route_to(:controller => "forum_sub_topics", :action => "create", :forum_topic_id => 1)

修改

哦,我的佣金路线看起来像这样:

car_follow_subscriptions_da POST   /biler/:car_id/car_subscriptions(.:format)                     {:action=>"create", :controller=>"car_subscriptions", :locale=>"da"}

1 个答案:

答案 0 :(得分:10)

rake routes提供的内容,我猜您应该替换:

 post :create, :car_id => 1, :car_subscription => valid_attributes

使用:

 post :create, :car_id => 1, :car_subscription => valid_attributes, :locale => "da"
相关问题