Module: ApiDocs::TestHelper::InstanceMethods

Defined in:
lib/api_docs/test_helper.rb

Instance Method Summary collapse

Instance Method Details

#api_call(method, path, params = { }) {|doc| ... } ⇒ Object

Method that allows test creation and will document results in a YAML file Example usage:

api_call(:get, '/users/:id', :id => 12345) do |doc|
  doc.description = 'Something for the docs'
  ... regular test code
end

Yields:

  • (doc)


10
11
12
13
14
15
16
17
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
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/api_docs/test_helper.rb', line 10

def api_call(method, path, params = { })
  parsed_params = params.dup
  parsed_path   = path.dup

  parsed_params.each do |k, v|
    parsed_params.delete(k) if parsed_path.gsub!(":#{k}", v.to_s)
  end
  
  if credentials = parsed_params.delete('HTTP_AUTHORIZATION')
    auth = {'HTTP_AUTHORIZATION' => credentials}
  end

  # Making actual test request. Based on the example above:
  #   get '/users/12345'
  doc = OpenStruct.new
  send(method, parsed_path, parsed_params, auth)

  yield doc if block_given?

  # Assertions inside test block didn't fail. Preparing file
  # content to be written
  c = request.filtered_parameters['controller']
  a = request.filtered_parameters['action']

  file_path = File.expand_path("#{c.gsub('/', ':')}.yml", ApiDocs.config.docs_path)
  params    = ApiDocs::TestHelper.api_deep_clean_params(params)

  # Marking response as an unique
  key = 'ID-' + Digest::MD5.hexdigest("
    #{method}#{path}#{doc.description}#{params}#{response.status}}
  ")

  data = if File.exists?(file_path)
    YAML.load_file(file_path) rescue Hash.new
  else
    Hash.new
  end

  data[a] ||= { }
  data[a][key] = {
    'description' => doc.description,
    'method'      => request.method,
    'path'        => path,
    'params'      => ApiDocs::TestHelper.api_deep_clean_params(params),
    'status'      => response.status,
    'body'        => response.body
  }
  FileUtils.mkdir_p(File.dirname(file_path))
  File.open(file_path, 'w'){|f| f.write(data.to_yaml)}
end