I find it troubling to test JSON API using RSpec request spec (see code below), because I have to create the required parameter every time (valid_attributes and invalid_attributes and it bothers me a LOT) I need to send a new request. It becomes harder to test when I need to send a request with an Authentication token (another requests?).
Is there a better approach to do so?
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 The gems I used for testing,
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