|
| 1 | +require "rspec_apib/version" |
| 2 | +require "rspec_apib/string_extensions" |
| 3 | + |
| 4 | +RSpec.configure do |config| |
| 5 | + config.before(:suite) do |example| |
| 6 | + api_docs_folder_path = File.join(Dir.pwd, '/api_docs/') |
| 7 | + Dir.mkdir(api_docs_folder_path) unless Dir.exists?(api_docs_folder_path) |
| 8 | + end |
| 9 | + |
| 10 | + config.after(:each, type: :controller) do |example| |
| 11 | + response ||= last_response |
| 12 | + request ||= last_request |
| 13 | + |
| 14 | + if response |
| 15 | + example_group = example.metadata[:example_group] |
| 16 | + example_groups = [] |
| 17 | + |
| 18 | + while example_group |
| 19 | + example_groups << example_group |
| 20 | + example_group = example_group[:parent_example_group] |
| 21 | + end |
| 22 | + |
| 23 | + action = example_groups[-2][:description_args].first if example_groups[-2] |
| 24 | + example_groups[-1][:description_args].first.match(/(\w+)\sRequests/) |
| 25 | + |
| 26 | + file_name = 'api' |
| 27 | + file = File.join(Dir.pwd, "/api_docs/#{file_name}.apib") |
| 28 | + |
| 29 | + File.open(file, 'a') do |f| |
| 30 | + # Resource & Action |
| 31 | + f.write "### #{action}\n\n" if [200, 201].include?(response.status) |
| 32 | + |
| 33 | + # Request |
| 34 | + request_body = request.body.read |
| 35 | + authorization_header = request.env ? request.env['HTTP_EH_AUTH'] : request.headers['HTTP_EH_AUTH'] |
| 36 | + |
| 37 | + if request_body.present? || authorization_header.present? |
| 38 | + f.write "+ Request (#{request.content_type})\n\n" |
| 39 | + |
| 40 | + # Request Headers |
| 41 | + if authorization_header.present? |
| 42 | + f.write "+ Headers\n".indent(2) |
| 43 | + f.write "HTTP_EH_AUTH: #{authorization_header}\n".indent(4) |
| 44 | + end |
| 45 | + |
| 46 | + f.write "\n" |
| 47 | + |
| 48 | + # Request Body |
| 49 | + if request_body.present? && request.content_type == 'application/json' |
| 50 | + f.write "+ Body\n".indent(2) if authorization_header |
| 51 | + f.write "#{JSON.pretty_generate(JSON.parse(request_body))}\n".indent(4) |
| 52 | + f.write "\n" |
| 53 | + end |
| 54 | + end if [200, 201].include?(response.status) |
| 55 | + |
| 56 | + # Response |
| 57 | + f.write "+ Response #{response.status} (#{response.content_type})\n\n" |
| 58 | + |
| 59 | + if response.body.present? && response.content_type =~ /application\/json/ |
| 60 | + f.write "+ Body\n".indent(2) |
| 61 | + f.write "#{JSON.pretty_generate(JSON.parse(response.body))}\n".indent(4) |
| 62 | + f.write "\n" |
| 63 | + end |
| 64 | + end |
| 65 | + end |
| 66 | + end |
| 67 | +end |
0 commit comments