Method: OpenStax::Api::RSpecHelpers#api_request

Defined in:
lib/openstax/api/rspec_helpers.rb

#api_request(type, action, doorkeeper_token, args = {}) ⇒ Object

Raises:

  • (IllegalArgument)


41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/openstax/api/rspec_helpers.rb', line 41

def api_request(type, action, doorkeeper_token, args={})
  raise IllegalArgument if ![:get, :post, :put, :delete, :patch, :head].include?(type)

  # Add the doorkeeper token info

  request.env['HTTP_AUTHORIZATION'] = "Bearer #{doorkeeper_token.token}" \
    if doorkeeper_token

  # Select the version of the API based on the spec metadata

  version_string = self.class.[:version].try(:to_s)
  raise ArgumentError, "Top-level 'describe' metadata must include a value for ':version'" if version_string.nil?
  request.env['HTTP_ACCEPT'] = "application/vnd.accounts.openstax.#{version_string}"

  # Set the raw post data in the request, converting to JSON if needed

  if args[:raw_post_data]
    request.env['RAW_POST_DATA'] = args[:raw_post_data].is_a?(Hash) ? 
                                   args[:raw_post_data].to_json : 
                                   args[:raw_post_data]
  end

  # Set the data format

  args[:parameters] ||= {}
  args[:parameters][:format] = 'json'

  # If these helpers are used from a request spec, action can
  # be a URL fragment string -- in such a case, prepend "/api"
  # to the front of the URL as a convenience to callers

  if action.is_a? String
    action = "/#{action}" if !action.starts_with?("/")
    action = "/api#{action}" if !action.starts_with?("/api/")
  end

  # Delegate the work to the normal HTTP request helpers
  self.send(type, action, args[:parameters], args[:session], args[:flash])
end