0
我發現使用RSpec請求規範(請參閱下面的代碼)測試JSON API令人煩惱,因爲我必須每次都創建所需的參數(valid_attributes
和invalid_attributes
和它困擾我很多)我需要發送一個新的請求。當我需要使用身份驗證令牌(另一個請求?)發送請求時,測試變得更加困難。什麼是使用RSpec請求規範測試JSON API的最佳方法
有沒有更好的方法來做到這一點?
describe 'POST /users' do
# valid payload
let(:valid_attributes) {
{
data: {
attributes: { email: '[email protected]', password: '1234' },
type: 'user'
}
}
}
# invalid payload
let(:invalid_attributes) {
{
data: {
attributes: { email: '', password: '' },
type: 'user'
}
}
}
context 'when the request is valid' do
before { post '/users', params: valid_attributes }
it 'creates a user' do
expect(response).to have_http_status(201)
end
end
context 'when the request is invalid' do
before { post '/users', params: invalid_attributes }
it 'create a user' do
expect(response).to have_http_status(422)
end
end
end
我測試用的寶石,
group :test do
gem 'rspec-rails', '~> 3.5'
# Use Factory Girl for generating random test data
gem 'factory_girl_rails', '~> 4.0'
gem 'shoulda-matchers', '~> 3.1'
gem 'faker'
gem 'database_cleaner'
end