gitlab-org--gitlab-foss/spec/support/api_helpers.rb
Rémy Coutable 5f7592d538 Implement json_response as a let variable
This is not a good idea to memoize `json_response` using an instance
variable because `rspec-retry` doesn't clear instance variables on
retries, only `let` variables.

This will avoid issues where retries would fail on a different line that
the original failure, blurrying what's the real failure.

Also, automatically add api: true to specs under
/spec/requests/(ci/)?api/, and include JsonHelpers in controller, request
and API specs.

Signed-off-by: Rémy Coutable <remy@rymai.me>
2017-03-13 17:33:17 +01:00

52 lines
1.3 KiB
Ruby

module ApiHelpers
# Public: Prepend a request path with the path to the API
#
# path - Path to append
# user - User object - If provided, automatically appends private_token query
# string for authenticated requests
#
# Examples
#
# >> api('/issues')
# => "/api/v2/issues"
#
# >> api('/issues', User.last)
# => "/api/v2/issues?private_token=..."
#
# >> api('/issues?foo=bar', User.last)
# => "/api/v2/issues?foo=bar&private_token=..."
#
# Returns the relative path to the requested API resource
def api(path, user = nil, version: API::API.version)
"/api/#{version}#{path}" +
# Normalize query string
(path.index('?') ? '' : '?') +
# Append private_token if given a User object
if user.respond_to?(:private_token)
"&private_token=#{user.private_token}"
else
''
end
end
# Temporary helper method for simplifying V3 exclusive API specs
def v3_api(path, user = nil)
api(path, user, version: 'v3')
end
def ci_api(path, user = nil)
"/ci/api/v1/#{path}" +
# Normalize query string
(path.index('?') ? '' : '?') +
# Append private_token if given a User object
if user.respond_to?(:private_token)
"&private_token=#{user.private_token}"
else
''
end
end
end