module RSpec::DeclarativeRequests::PerformRequest

Constants

HTTP_METHODS

Public Instance Methods

call(example) click to toggle source
# File lib/rspec/declarative_requests.rb, line 18
    def call(example)
      group = ([RSpec.current_example] + example.class.parent_groups).find do |group|
        HTTP_METHODS.any? do |http_method|
          group.description.start_with?(http_method + ' ')
        end
      end

      if group.nil?
        raise Error, <<~END_ERROR
          Could not find an RSpec example group that looks like a request. The
          describe/context description must start with an uppercase HTTP verb
          like "GET" or "POST".

          Try something like:

            describe "GET /foo" do
              it { is_expected.to have_http_status(:ok) }
            end
        END_ERROR
      end

      method, _, path = group.description.partition(/\s+/)
      example.send(
        method.downcase,
        interpolate(path, example),
        params: example.params,
        headers: example.headers,
      )
    end
interpolate(path, example) click to toggle source
# File lib/rspec/declarative_requests.rb, line 48
def interpolate(path, example)
  path.gsub(/\:[a-z_#]+/) do |match|
    match[1..-1].split('#').reduce(example) do |value, attr|
      if value.is_a?(Hash)
        case
        when value.key?(attr) then value[attr]
        when value.key?(attr.to_sym) then value[attr.to_sym]
        else raise Error, "Couldn't find '#{attr}' while interpolating '#{match}' in the request path"
        end
      else
        value.send(attr)
      end
    end
  end
end