Module: RSpec::DeclarativeRequests::PerformRequest

Extended by:
PerformRequest
Included in:
PerformRequest
Defined in:
lib/rspec/declarative_requests.rb

Constant Summary collapse

HTTP_METHODS =
%w(CONNECT DELETE GET HEAD OPTIONS PATCH POST PUT TRACE)

Instance Method Summary collapse

Instance Method Details

#call(example) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# 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) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# 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