ryz310/my_api_client

View on GitHub
lib/generators/rspec/templates/api_client_spec.rb.erb

Summary

Maintainability
Test Coverage
# frozen_string_literal: true

require 'rails_helper'

RSpec.describe <%= "#{class_name}ApiClient" %>, <%= type_metatag(:api_client) %> do
  let(:api_client) { described_class.new }
  let(:headers) do
    {
      'Content-Type': 'application/json',
    }
  end

  shared_examples 'to handle errors' do
    context 'when the API returns 200 OK' do
      it do
        expect { api_request }
          .not_to be_handled_as_an_error
          .when_receive(status_code: 200)
      end
    end

    context 'when the API returns 400 Bad Request' do
      it do
        expect { api_request }
          .to be_handled_as_an_error(MyApiClient::ClientError::BadRequest)
          .when_receive(status_code: 400)
      end
    end
  end
<% yeild_request_arguments do |action, http_method, pathname| -%>

  describe '#<%= action %>' do
    subject(:api_request) { api_client.<%= action %> }

    it_behaves_like 'to handle errors'

    it do
      expect { api_request }
        .to request_to(:<%= http_method %>, '<%= options[:endpoint] %>/<%= pathname %>')
<% if http_method == 'get' -%>
        .with(headers: headers, query: {})
<% else -%>
        .with(headers: headers, body: {})
<% end -%>
    end
  end
<% end -%>
end