2017-08-25 22 views
1

我正在編寫rails api的驗收規範。我能夠在請求規範中做到這一點,但我想構建驗收規範,以便使用rspec_api_documentation gem生成文檔。在驗收規範中使用令牌驗證測試rails api的正確方法是什麼?

我的要求的規格如下所示:

let(:headers) { { 'accept': 'application/json' } } 
let(:user) { users(:jane) } 

describe '#show' do 
    let(:endpoint) { "/api/v1/users/#{user.username}" } 

    context 'when authenticated' do 
     let(:expected_response) { "{\"user\":#{user.to_builder.target!}}" } 
     let(:headers) { { 'Authorization': token, 'accept': 'application/json' } } 
     let(:token) do 
     post '/api/v1/authenticate', 
      params: { email: user.email, password: 'testpassword' }, 
      headers: { 'accept': 'application/json' } 
     JSON.parse(response.body)['auth_token'] 
     end 

     it 'I can get user info' do 
     get endpoint, params: {}, headers: headers 
     expect(response.content_type).to eq("application/json") 
     expect(response.body).to eq expected_response 
     end 
    end 
end 

到目前爲止,我有這個,但它不工作,因爲讓變量是無法訪問外例子組。

RSpec.resource 'Users' do 
    header 'Accept', 'application/json' 
    header 'Content-Type', 'application/json' 
    get '/api/v1/users/:id' do 
    explanation 'First, get an auth token, then request user info' 

    fixtures :users 

    let(:auth_token) do 
     client.post '/api/v1/authenticate', 
        params: { email: user.email, password: 'testpassword' }, 
        headers: { 'accept': 'application/json' } 
     JSON.parse(response_body)['auth_token'] 
    end 
    let(:id) { user.id } 
    let(:user) { users(:jane) } 

    header 'Authorization', auth_token 

    example_request 'Getting a specific user' do 
     expect(response_body).to eq(user.to_json) 
     expect(status).to eq(200) 
    end 
    end 
end 

回答

1

docs of the gem

該方法以標題名稱和值。該值可以是字符串或符號。如果它是一個符號,它將發送符號,允許您設置標題值。

在此基礎上,我認爲你必須聲明的標題是這樣的:

header 'Authorization', :auth_token 

看一看在文檔下方引用段落的例子。

相關問題