2016-05-30 63 views
0

我正在嘗試在Rails中爲RSpec get JSON API測試添加授權令牌。但到目前爲止,所有嘗試都會導致錯誤。問題似乎是令牌沒有在請求中正確傳遞。如何在RSpec測試中爲JSON API傳遞身份驗證令牌?

expected the response to have a success status code (2xx) but it was 401 

當前代碼:

Project_spec.rb(測試)

before do 
    @project = create(:project, :key => "123") 
    get '/api/v1/projects/1', {:Authorization => "Token 123"}, format: :json 
end 

it "returns correct status" do 
    expect(response).to have_http_status(:success) 
end 

ProjectsController.rb

before_filter :restrict_access, :except => :create 

def show 
    @project = Project.find(params[:id]) 
    render json: @project 
end 

def restrict_access 
    authenticate_or_request_with_http_token do |token, options| 
     Project.exists?(key: token) 
    end 
end 

基於幾個推薦的解決方案在網上找到的,我我試過

  1. get '/api/v1/projects/1', format: :json, token: "123"

  2. get '/api/v1/projects/1', { 'HTTP-AUTHORIZATION' => 'Token "123"' }, format: :json

  3. get '/api/v1/projects/1', {:Authorization => "Token 123"}, format: :json

但似乎沒有成功通過授權令牌。

注意:#3中的樣式在從外部應用程序發佈時工作,但不在RSpec測試本身中。

有沒有人有這方面的經驗,可以分享一些方向?

回答

6

使用它像:

get '/api/v1/projects/1', {}, { Authorization: "Token 123"} 

get是HTTP方法,{}空參數,可以{ :Authorization => "Token 123"}

的get(路徑,參數=零,headers_or_env =無)

Documentation

其他方式:

before do 
    # some code here 
    @request.env['Authorization'] = "Token 123" 
    get '/api/v1/projects/1', format: :json 
end 
+0

什麼是空的則params的目的是什麼? –

+2

如果你忽略它,那麼'{Authorization:「Token 123」}'識別爲參數而不是頭部。 –

0

它工作時,我只是想這樣

get '/api/v1/projects/1', as: :json, headers: {:Authorization => "Token 123"}