Skip to content

Examples

Joel Tannas edited this page Nov 27, 2022 · 10 revisions

Documenting a query parameter

OAS2:

parameter name: :coin, in: :query, type: :string

OAS3:

parameter name: :coin, in: :query, schema: { type: string }

Documenting a query parameter with a list of allowed values

parameter name: :coin, in: :query, type: :string, enum: ['penny', 'nickel', 'dime', 'quarter']

Documenting a nullable enum parameter

parameter(
  name: :coin,
  in: :query,
  type: :string,
  nullable: true,
  enum: [nil, 'penny', 'nickel', 'dime', 'quarter']
)

Source: https://github.com/rswag/rswag/issues/221#issuecomment-557547085

Documenting a custom header parameter

parameter(
  name: 'X-Key-Inflection',
  in: :header,
  schema: {
    type: :string,
    enum: ['snake', 'camel', 'dash', 'pascal'],
  },
  required: false,
  default: 'camel',
)

Documenting a response that is an array of objects

schema type:  :array, items: { '$ref' => '#/definitions/profile_search' }

Credit to @heaven for the example https://github.com/rswag/rswag/issues/195#issuecomment-463977357

Documenting a 5XX Error Response

response '502', 'Bad Gateway' do
  let(:Authorization) { external_api_token }

  schema(
    type: :object,
    properties: {
      status: { type: :string, enum: ['502'] },
      message: { type: :string, enum: ['Bad Gateway'] },
      description: { type: :string },
    },
  )

  before do |example|
    allow_any_instance_of(ExampleController).to receive(:create).and_raise BadGateway
    suppress(BadGateway) { submit_request(example.metadata) }
  end

  it 'returns an appropriate error description JSON' do |example|
    assert_response_matches_metadata(example.metadata)
  end
end

Documenting an array query parameter

See Here

Using RSpec subject style assertions without using run_test!

Source: https://github.com/rswag/rswag/pull/363

RSpec.describe "API" do
  subject(:api_request) { |example| submit_request(example.metadata) }
  response '200', 'Okay' do
    context 'when a valid request is made' do
      it 'creates a new user' do |example|
        expect { api_request }.to change(User, :count).by(1)
        assert_response_matches_metadata(example.metadata)
      end
    end
  end
end