Techioz Blog

10 進数の応答が文字列として返される場合、RSpec/RSwag で 10 進数のスキーマ形式を指定するにはどうすればよいですか?

概要

そのため、:Decimal 形式の DB フィールドが文字列として返され、テストが失敗します。

RSwag を使用したリクエスト仕様があり、それを形式チェックで通過させようとしていますが、次のようなメッセージが表示されます。

Rswag::Specs::UnexpectedResponse:
       Expected response body to match schema: The property '#/budget' of type string did not match the following type: number in schema 

私のテスト:-

 path '/api/v1/jobs/{id}' do
    parameter name: 'id', in: :path, type: :string, description: 'Job id'

    get('show job') do
      tags 'Jobs'
      response(200, 'successful') do
        schema type: :object,
               properties: {
                 title: { type: :string },
                 description: { type: :string },
                 date: { type: :string, format: 'date-time', nullable: true  },
                 budget: { type: :number, format: 'double' },
                 awarded: { type: :boolean },
                 created_at: { type: :datetime},
                 updated_at: { type: :datetime}
               }
        let(:id) { @job.id }

        after do |example|
          example.metadata[:response][:content] = {
            'application/json' => {
              example: JSON.parse(response.body, symbolize_names: true)
            }
          }
        end
        run_test!
      end
    end

これを回避する最善の方法は何でしょうか?すべてのフィールドを文字列にする必要がある場合、API ドキュメントに Swagger を使用する努力は少し無意味です。

解決策

タイプを :string に設定し、フォーマットとして 10 進数を使用しました。私の場合はこれでうまくいきました。

シナリオでは、以下を使用できます。

budget: { type: :string, format: 'decimal' },