2011-07-16 90 views
6

我有2個控制器,我使用軌道的腳手架發電機創建。我希望他們可以嵌套一個名爲「演示」文件夾中,因此跑如何使用Rspec測試具有嵌套路由的控制器?

rails g scaffold demo/flows 
rails g scaffold demo/nodes 

然後,我決定內部流動窩節點,並改變了我的路線文件,像這樣:

namespace :demo do 
    resources :flows do 
    resources :nodes 
    end 
end 

但這種改變導致rspec測試的節點違反了ActionController :: Routing錯誤。

15) Demo::NodesController DELETE destroy redirects to the demo_nodes list 
    Failure/Error: delete :destroy, :id => "1" 
    ActionController::RoutingError: 
     No route matches {:id=>"1", :controller=>"demo/nodes", :action=>"destroy"} 

問題是rspec正在看錯誤的路線。它應該尋找「演示/流量/ 1 /節點」。它也需要模擬流程模型,但我不知道如何提供。這裏是我生成的rspec文件的示例代碼:

def mock_node(stubs={}) 
    @mock_node ||= mock_model(Demo::Node, stubs).as_null_object 
    end 

    describe "GET index" do 
    it "assigns all demo_nodes as @demo_nodes" do 
     Demo::Node.stub(:all) { [mock_node] } 
     get :index 
     assigns(:demo_nodes).should eq([mock_node]) 
    end 
    end 

有人可以幫我理解我需要如何提供流模型嗎?

回答

15

你有兩個不同的問題在這裏進行,所以你可能想分開它們,因爲你的第二個問題與這篇文章的標題無關。我會建議使用FactoryGirl用於創建模擬模型https://github.com/thoughtbot/factory_girl

您的路線錯誤是從你的嵌套的路線需要這樣他們每個人之後的id的事實來:

/demo/flows/:flow_id/nodes/:id 

當你做對的刪除對象,你需要傳入流程ID,否則它不會知道你在說什麼路線。

delete :destroy, :id => "1", :flow_id => "1" 

今後,要檢查什麼,預計最簡單的方法是運行rake routes,併爲這條路線的輸出與你PARAMS你所傳遞的比較。

demo_flow_node /demo/flows/:flow_id/nodes/:id(.:format) {:action=>"destroy", :controller=>"demo/flows"}