所以我正在编写一些返回并处理json的API控制器。一个特殊的是会话控制器。我这样设置路线:
注意:(我只向您展示销毁方法,因为这是我唯一遇到问题的方法......)
namespace :api do
namespace :v1 do
resource :users
resources :sessions
end
end
然后我有以下路线:
api_v1_sessions GET /api/v1/sessions(.:format) api/v1/sessions#index
POST /api/v1/sessions(.:format) api/v1/sessions#create
new_api_v1_session GET /api/v1/sessions/new(.:format) api/v1/sessions#new
edit_api_v1_session GET /api/v1/sessions/:id/edit(.:format) api/v1/sessions#edit
api_v1_session GET /api/v1/sessions/:id(.:format) api/v1/sessions#show
PATCH /api/v1/sessions/:id(.:format) api/v1/sessions#update
PUT /api/v1/sessions/:id(.:format) api/v1/sessions#update
DELETE /api/v1/sessions/:id(.:format) api/v1/sessions#destroy
最后,我为api/v1/sessions#destroy
:
def destroy
@user = User.find_by auth_token: param[:auth_token]
return invalid_user_crendentials unless @user
cookies.delete(@user.auth_token)
render json: { user_id: @user.id }, status: 200
end
然后我为这个特定的动作编写了以下规范测试:
context "Destroy a session" do
it "should NOT destroy a session" do
post :destroy
response.response_code.should == 401
end
it "should NOT destroy a session with invalid token" do
post :destroy, auth_token: '34534534'
response.response_code.should == 401
end
it "should destroy a session based on valid data" do
post :destory, auth_token: @user.auth_token
json = JSON.parse response.body
json.to_json.should have_json_path('user_id')
response.response_code.should == 200
end
end
但是当我跑步时,我得到了:
No route matches {:auth_token=>"34534534", :controller=>"api/v1/sessions", :action=>"destroy"}
No route matches {:auth_token=>"QfEg4oa0UdhJF4K1VIBADg", :controller=>"api/v1/sessions", :action=>"destory"}
No route matches {:controller=>"api/v1/sessions", :action=>"destroy"}
没有路线匹配?一点都没有?
答案 0 :(得分:1)
将post
更改为delete
context "Destroy a session" do
it "should NOT destroy a session" do
delete :destroy
response.response_code.should == 401
end
it "should NOT destroy a session with invalid token" do
delete :destroy, auth_token: '34534534'
response.response_code.should == 401
end
it "should destroy a session based on valid data" do
delete :destory, auth_token: @user.auth_token
json = JSON.parse response.body
json.to_json.should have_json_path('user_id')
response.response_code.should == 200
end
end
您可以在rake routes
输出中看到您的销毁操作仅接受delete
次请求:
DELETE /api/v1/sessions/:id(.:format) api/v1/sessions#destroy
它还在寻找一个:id
参数。我想您想要在控制器中将param[:auth_token]
更改为param[:id]
,并在规范中将auth_token
更改为id
。
答案 1 :(得分:1)
您的路线都希望传递id
参数。
DELETE /api/v1/sessions/:id
您的测试正在传递auth_token
。更改测试以传递id
。
注意:您的测试确实应该是delete :destroy
而不是post
,而您的第三次测试也会在:destroy
中出现拼写错误。