我想用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
運行耙路線看看現有的路線可用。 – hamitron