2011-12-13 59 views
2

我试图做一个测试嵌套的资源控制器测试嵌套的资源控制器。与Rails的rspec的3.1

嵌套就是这样在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 

它实际上是由轨道生成的支架的一部分脚本。我只修改了valid_attributes并在第一“它”

,输出是这样的帖子:

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)>' 

它是所有相同的错误“是。

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

其实我已经分手了这么car_subscriptions的index资源和destroy在没有嵌套,createnew嵌套在:cars

我不想在这个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"} 

回答

10

从什么rake routes提供,我想你应该更换:

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

有:

post :create, :car_id => 1, :car_subscription => valid_attributes, :locale => "da" 
+0

呀!你说得对,这是奇怪的,这应该是更好地记录在[RubyOnRails指南](http://guides.rubyonrails.org/testing.html#what-to-include-in-your-functional-tests)! – Cristian 2011-12-13 23:39:02