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