LoginSignup
0
0

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-04-18

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

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

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

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

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

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0