2016-08-23 33 views
0

我想做一些單元測試,這是我第一次。我不明白爲什麼有No route matchesRails單元測試:沒有路由匹配爲什麼?

當我運行$ rake test test/controllers/products_controller_test.rb

我得到這個在控制檯輸出:

1) Error: 
ProductsControllerTest#test_should_get_edit: 
ActionController::UrlGenerationError: No route matches {:action=>"edit", :controller=>"products"} 
    test/controllers/products_controller_test.rb:20:in `block in <class:ProductsControllerTest>' 


    2) Error: 
ProductsControllerTest#test_should_get_show: 
ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"products"} 
    test/controllers/products_controller_test.rb:35:in `block in <class:ProductsControllerTest>' 


    3) Error: 
ProductsControllerTest#test_should_get_create: 
ActionController::ParameterMissing: param is missing or the value is empty: product 
    app/controllers/products_controller.rb:59:in 'product_params' 
    app/controllers/products_controller.rb:18:in 'create' 
    test/controllers/products_controller_test.rb:15:in `block in <class:ProductsControllerTest>' 


    4) Error: 
ProductsControllerTest#test_should_get_update: 
ActionController::UrlGenerationError: No route matches {:action=>"update", :controller=>"products"} 
    test/controllers/products_controller_test.rb:25:in `block in <class:ProductsControllerTest>' 


    5) Error: 
ProductsControllerTest#test_should_get_destroy: 
ActionController::UrlGenerationError: No route matches {:action=>"destroy", :controller=>"products"} 
    test/controllers/products_controller_test.rb:30:in `block in <class:ProductsControllerTest>' 

7 runs, 2 assertions, 0 failures, 5 errors, 0 skips 

這是products_controller_test.rb文件:

require 'test_helper' 

class ProductsControllerTest < ActionController::TestCase 
    test "should get index" do 
    get :index 
    assert_response :success 
    end 

    test "should get new" do 
    get :new 
    assert_response :success 
    end 

    test "should get create" do 
    get :create 
    assert_response :success 
    end 

    test "should get edit" do 
    get :edit 
    assert_response :success 
    end 

    test "should get update" do 
    get :update 
    assert_response :success 
    end 

    test "should get destroy" do 
    get :destroy 
    assert_response :success 
    end 

    test "should get show" do 
    get :show 
    assert_response :success 
    end 

end 

routes.rb文件:

Rails.application.routes.draw do 
    resources :products 
end 

回答

1

對於所有這些路線(編輯,更新,銷燬),你需要說產品,您正在編輯/更新/銷燬。如果Rails不知道它,它不能爲你繪製路線。

對於編輯,例如,完整的路線將是products/:product_id/edit。所以Rails需要'填寫':product_id鍵。如果您將其留空,則路由中斷。

在你的代碼中,如果你打電話給get :edit,你需要指定一個產品ID。像這樣:

get :edit, product_id: products(:test_product).id

(使用固定裝置滑軌測試教程 here解釋)
相關問題