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, "      Could not find an RSpec example group that looks like a request. The\n      describe/context description must start with an uppercase HTTP verb\n      like \"GET\" or \"POST\".\n\n      Try something like:\n\n        describe \"GET /foo\" do\n          it { is_expected.to have_http_status(:ok) }\n        end\n    END_ERROR\n  end\n\n  method, _, path = group.description.partition(/\\s+/)\n  example.send(\n    method.downcase,\n    interpolate(path, example),\n    params: example.params,\n    headers: example.headers,\n  )\nend\n"

#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