【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
Author And Source
この問題について(【3分入門】コピペで導入!Rails API server のテストに json-schema を使う), 我々は、より多くの情報をここで見つけました https://qiita.com/nishisuke/items/79358649a7154ba7bf9c著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .