【3分入門】コピペで導入!Rails API server のテストに json-schema を使う


【3分入門】 コピペで導入!シリーズです。

API server の json を担保したいというのは人類共通の思いかと思います。

そんなあなたはgraphqlを使えばそんな悩みも軽減されるかもしれません。

全員が全員, rest apiからgraphqlに乗り換えれるわけではないので、

テストを書いていきましょう!

json schemaとは

ietfに定義されています。

jsonの構造をjsonで表現します。

こんな感じ

schema = {
  "type" => "object",
  "properties" => {
    "message" => {"type" => "string"}
  }
}

この定義はこのjsonの表現です。

{
  message: 'Hello world!'
}

キーと型を記述していく感じです。

rspec + factorybot code

spec/requests/users_request_spec.rb
RSpec.describe 'users API', type: :request do
  let(:user) { create(:user) }
  let(:res) { YAML.load_file(File.expand_path("../fixtures/res/#{res_name}.yml", __dir__)).to_json }

  before do
    get url, { headers: { Authorization: "Bearer #{user.token}" } }
  end

  shared_examples 'valid json' do
    it 'successes' do
      expect { JSON::Validator.validate!(res, response.body, version: :draft4, strict: true, json: true) }.not_to raise_error
    end
  end

  describe 'GET #index' do
    let(:res_name) { 'user' }
    let(:url) { me_url }

    it_behaves_like 'valid json'
  end
end
spec/fixtures/res/user.yml
type: object
properties:
  id:
    type: integer
  name:
    type: string
  age:
    type: integer