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