ruby-on-railsrspecruby-on-rails-5rswag

rswag gem: what is the main purpose of schema in the response block?


describe 'Blogs API' do

  path '/blogs' do

    post 'Creates a blog' do

      response 422, 'invalid request' do
        **schema** '$ref' => '#/definitions/errors_object'
  ...
end

What is the benefit of keyword schema in the above code for us? Does the real response compare to that? and if not match, raise an error?


Solution

  • Yes, rswag will validate that your API response matches the schema you have specified when running the tests. It'll also output the schema as the 'Model' in the generated swagger documentation.

    In the example you have given it will look up errors_object within your config.swagger_docs. The rswag documentation shows you how to define it:

    config.swagger_docs = {
      'v1/swagger.json' => {
        swagger: '2.0',
        info: {
          title: 'API V1'
        },
        definitions: {
          errors_object: {
            type: 'object',
            properties: {
              errors: { '$ref' => '#/definitions/errors_map' }
            }
          },
          errors_map: {
            type: 'object',
            additionalProperties: {
              type: 'array',
              items: { type: 'string' }
            }
          }
        }
      }
    }