Skip to content

Instantly share code, notes, and snippets.

@smsohan
Created May 22, 2012 16:49
Show Gist options
  • Save smsohan/2770197 to your computer and use it in GitHub Desktop.
Save smsohan/2770197 to your computer and use it in GitHub Desktop.
API Doc from Tests
#Example Spec, cities_controller_spec.rb
require 'spec_helper'
describe CitiesController do
include Apify
describe 'cities api' do
before(:each) do
City.create!(:name => 'Dhaka', :country => 'Bangladesh')
end
it 'Returns a json list of cities' do
get :index, :my_data => 1, :format => :json
response.should be_success
end
describe 'New city' do
it 'Creates a city with json data' do
post :create, :city => {:name => 'Toronto', :country => 'Canada'}, :format => :json
response.should be_success
end
end
end
end
#####################
#Apify module
module Apify
def self.included base
create_api_file
base.after(:each) do
generate_api
end
end
def self.create_api_file
FileUtils.mkdir_p File.dirname(api_file_name)
@@apify_file = File.open(api_file_name, 'w+')
end
def apify_file
@@apify_file
end
def api_index
@@api_index ||= 1
end
def generate_api
apify_file.puts "<strong>" + example.description + "</strong>"
apify_file.puts "<pre>"
apify_file.puts api_index
log_request response.request
apify_file.puts
log_response response
apify_file.puts "</pre>"
@@api_index += 1
end
def log_request request
apify_file.puts "REQUEST"
request_method_path = "#{request.method} #{request.path}"
request_method_path += "?#{request.query_parameters.to_param}" if request.query_parameters.present?
apify_file.puts request_method_path
apify_file.puts request.formats.join(',')
apify_file.puts(JSON.pretty_generate(request.request_parameters.as_json)) if request.request_parameters.present?
end
def log_response response
apify_file.puts "RESPONSE"
apify_file.puts response.header['Content-Type']
apify_file.puts JSON.pretty_generate(JSON.parse(response.body))
end
def self.api_file_name
File.join(Rails.root, 'apify', "api.html")
end
end
###########################
## Example Output
<strong>Returns a json list of cities</strong>
<pre>
1
REQUEST
GET /cities.json?my_data=1
application/json
RESPONSE
application/json; charset=utf-8
[
{
"city": {
"country": "Bangladesh",
"created_at": "2011-08-29T19:08:15Z",
"id": 1,
"name": "Dhaka",
"updated_at": "2011-08-29T19:08:15Z"
}
}
]
</pre>
<strong>Creates a city with json data</strong>
<pre>
2
REQUEST
POST /cities.json
application/json
{
"city": {
"name": "Toronto",
"country": "Canada"
}
}
RESPONSE
application/json; charset=utf-8
{
"city": {
"country": "Canada",
"created_at": "2011-08-29T19:08:15Z",
"id": 2,
"name": "Toronto",
"updated_at": "2011-08-29T19:08:15Z"
}
}
</pre>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment