Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

test helper

  • Loading branch information...
commit 67095617258233f63ae767394063f4c0198bab78 1 parent e9f7963
@GBH GBH authored
View
1  lib/api_docs.rb
@@ -1,5 +1,6 @@
require 'api_docs/engine'
require 'api_docs/configuration'
+require 'api_docs/test_helper'
module ApiDocs
View
17 lib/api_docs/configuration.rb
@@ -1,13 +1,10 @@
-module ApiDocs
- class Configuration
-
- # Where to find the folder with documentation files
- attr_accessor :docs_path
-
- # Configuration defaults
- def initialize
- @docs_path = Rails.root.join('doc/api')
- end
+class ApiDocs::Configuration
+
+ # Where to find the folder with documentation files
+ attr_accessor :docs_path
+ # Configuration defaults
+ def initialize
+ @docs_path = Rails.root.join('doc/api')
end
end
View
61 lib/api_docs/test_helper.rb
@@ -0,0 +1,61 @@
+module ApiDocs::TestHelper
+
+ # Method that allows test creation and will document results in a YAML file
+ # Example usage:
+ # api_call(:get, '/users/:id', :id => 99) do |doc|
+ # doc.description = 'Something for the docs'
+ # ... regular test code
+ # end
+ def api_call(method, path, params = { }, &block)
+ data_path = path.dup
+ data_params = params.dup.stringify_keys
+
+ params.each do |k, v|
+ params.delete(k) if path.gsub!(":#{k}", v)
+ end
+ send(method, path, params)
+ doc = OpenStruct.new
+ yield doc
+
+ controller = request.filtered_parameters['controller']
+ action = request.filtered_parameters['action']
+ file_path = File.expand_path("#{controller.gsub('/', ':')}.yml", ApiDocs.config.docs_path)
+ params = api_deep_clean_params(params)
+ key = Digest::SHA1.base64digest("#{method}#{path}#{params}#{response.status}#{response.body}")
+
+ data = if File.exists?(file_path)
+ YAML.load_file(file_path) rescue Hash.new
+ else
+ Hash.new
+ end
+
+ data[action] ||= { }
+ data[action][key] = {
+ 'description' => doc.description,
+ 'method' => request.method,
+ 'path' => data_path,
+ 'params' => api_deep_clean_params(data_params),
+ 'status' => response.status,
+ 'body' => JSON.parse(response.body)
+ }
+ File.open(file_path, 'w'){|f| f.write(data.to_yaml)}
+ end
+
+ # Cleans up params. Removes things like File object handlers
+ def api_deep_clean_params(params)
+ result = { }
+ params.each do |key, value|
+ result[key.to_s] = case value
+ when Hash
+ api_deep_clean_params(value)
+ when Rack::Test::UploadedFile
+ 'BINARY'
+ else
+ value.to_s
+ end
+ end
+ result
+ end
+end
+
+ActionDispatch::IntegrationTest.send :include, ApiDocs::TestHelper
Please sign in to comment.
Something went wrong with that request. Please try again.