XYZ
XYZ

Reputation: 27397

What is the best approach to test JSON API using RSpec request spec

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

Upvotes: 1

Views: 798

Answers (1)

Marko Avlijaš
Marko Avlijaš

Reputation: 1659

Not sure what you had in mind, but I'd remove duplication like this:

def user_with(email: '', password: '')
  {
    data: {
      attributes: { email: email, password: password },
      type: 'user'
    }
  }
end

# valid payload
let(:valid_attributes) { user_with(email: '[email protected]', password: '1234') }

# invalid payload
let(:invalid_attributes) { user_with() }

Obviously move that in a module or shared_context in some file in support dir if you need to reuse it accross several spec files.

Upvotes: 2

Related Questions