Sha256: a59878b05715c7a7c9bd49e019443e5ee39951b5d6fa1e36db50394f49cec9c8

Contents?: true

Size: 1.88 KB

Versions: 1

Compression:

Stored size: 1.88 KB

Contents

require 'rspec/request_describer/version'

module RSpec
  module RequestDescriber
    RESERVED_HEADER_NAMES = %w[
      content-type
      host
      https
    ].freeze

    SUPPORTED_METHODS = %w[
      DELETE
      GET
      HEAD
      PATCH
      POST
      PUT
    ].freeze

    class << self
      def included(base)
        base.instance_eval do
          subject do
            send_request
          end

          let(:send_request) do
            send(
              http_method,
              path,
              headers: env,
              params: request_body
            )
          end

          let(:request_body) do
            if headers.any? { |key, value| key.to_s.casecmp('content-type').zero? && value == 'application/json' }
              params.to_json
            else
              params.inject({}) do |result, (key, value)|
                result.merge(key.to_s => value)
              end
            end
          end

          let(:headers) do
            {}
          end

          let(:params) do
            {}
          end

          let(:env) do
            headers.inject({}) do |result, (key, value)|
              key = key.to_s
              key = 'HTTP_' + key unless RESERVED_HEADER_NAMES.include?(key.downcase)
              key = key.tr('-', '_').upcase
              result.merge(key => value)
            end
          end

          let(:endpoint_segments) do
            current_example = ::RSpec.respond_to?(:current_example) ? ::RSpec.current_example : example
            current_example.full_description.match(/(#{::Regexp.union(SUPPORTED_METHODS)}) (\S+)/).to_a
          end

          # @return [String] e.g. `"get"`
          let(:http_method) do
            endpoint_segments[1].downcase
          end

          let(:path) do
            endpoint_segments[2].gsub(/:(\w+[!?=]?)/) { send(Regexp.last_match(1)) }
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rspec-request_describer-0.4.0 lib/rspec/request_describer.rb