2015-09-23 80 views
1

我想用RSpec測試我的API。嵌套的API:ActionController :: UrlGenerationError - 沒有路由匹配

Api :: V1 :: EventsController存在並且有一個create方法。我使用simple_token_authentication和pundit來確保安全性。

的routes.rb

Rails.application.routes.draw do 
    namespace :api do 
    namespace :v1 do 
     # users/ 
     resources :users, only: [:show, :update] do 
     # users/:id/events/ 
     resources :events 
     end 
    end 
    end 
end 

規格:

RSpec.describe Api::V1::EventsController, type: :controller do 

    describe 'events#create' do 
    before { 
     @user = User.create(email: '[email protected]', password: '12345678', password_confirmation: '12345678') 
     @user.reload 
    } 

    it 'should 401 if bad credentials' do 
     # Given the user 

     # When 
     post "/api/v1/users/#{@user.id}/events", {}, 
     { 
     'x-user-email' => 'toto', 
     'x-user-token' => 'toto' 
     } 

     # Then 
     expect_status 401 
    end 
    end 
end 

,我得到這個錯誤:

Failure/Error: post "/api/v1/users/#{@user.id}/events", {}, 
    ActionController::UrlGenerationError: 
    No route matches {:action=>"/api/v1/users/1/events", :controller=>"api/v1/events"} 

編輯和答案: 我很困惑,我使用RSpec的控制器當我想使用rspec請求。 這是我的工作例如:

RSpec.describe Api::V1::EventsController, type: :controller do 

    describe 'events#create' do 
    before { 
     @user = User.create(email: '[email protected]', password: '12345678', password_confirmation: '12345678') 
     @user.reload 
    } 

    it 'should 401 if bad credentials' do 
     # Given the user 

     # When 
     post "/api/v1/users/#{@user.id}/events", {}.to_json, 
     { 
     'Accept' => 'application/json', 
     'Content-Type' => 'application/json', 
     'x-user-email' => 'toto', 
     'x-user-token' => 'toto' 
     } 

     # Then 
     expect_status 401 
    end 
    end 
end 
+0

運行耙路線看看現有的路線可用。 – hamitron

回答

3

在控制器規範的post方法接受一個動作名稱的第一個參數,而不是一個路徑,所以不是:

post "/api/v1/users/#{@user.id}/events", #... 

嘗試:

post :create, #... 

控制器規格是單元測試。如果要測試整個堆棧,請使用feature spec而不是控制器規範。

+0

謝謝。我不明白控制器測試是單元測試。我現在正在使用請求測試,它工作。 –

3

因爲您已經在測試Api :: V1 :: EventsController,所以您不需要使用完整路徑執行請求。

因此,這將是更好的使用它特殊的語法:如果你想測試路線

post :create, nil, { 
    'x-user-email' => 'toto', 
    'x-user-token' => 'toto' 
} 

expect(response.response_code).to eq 401 

,你應該這樣做的途徑規格:

# spec/routing/api_v1_events_routing_spec.rb 
require "spec_helper" 

RSpec.describe Api::V1::EventsController do 
    describe "routing" do 
    it "#create" do 
     expect(post: "/api/v1/users/1/events").to \ 
     route_to(controller: "api/v1/events", action: "create", user_id: "1") 
    end 
    end 
end 
相關問題