LoginSignup
3
2

More than 1 year has passed since last update.

JSONを受け渡しするRails APIのrequest specの書き方

Last updated at Posted at 2022-08-18

はじめに

一部React化で久しぶりにAPIを作成しました
JSONを受け渡しするRails APIのrequest specの書き方まとめです :sparkles:

headersにContent-Typeを追加する

headersに'Content-Type' => 'application/json'を追加する
これでJSONのparamsを渡すことができるようになります

追加しないとデフォルトでは
"CONTENT_TYPE"=>"multipart/form-data"となり
数値やbooleanが文字列に変換されてしまいます

  describe 'PATCH #update' do
    subject { patch xxx_path(article), headers: { "Content-Type" => "application/json" } }
    ...
  end

JSONのparamsを用意する

let!(:params) { { name: 'タイトル', body: '本文' }.to_json }

to_json を使ってHashからJSONにパースするのがポイント
パースしないと
ActionDispatch::Http::Parameters::ParseError
を吐いて500が帰ってきます :sweat_drops:

requestにparamsを渡す

  describe 'PATCH #update' do
    subject { patch xxx_path, params: params, headers: { "Content-Type" => "application/json" } }
    ...
  end

テストする

as_jsonはハッシュのキーをシンボルから文字列に変換してくれます :raised_hands_tone1:
最初から文字列のハッシュを書いてもOKですが、キーがシンボルの方がスッキリするので今回はシンボルで定義してからas_jsonしています

  it 'creates article and returns correct response' do
    expect { subject }.to change(Article, :count).by(1)
    expect(Article.last.name).to eq 'タイトル'
    expect(Article.last.name).to eq '本文'
    expect(response).to have_http_status 200
    expect(JSON.parse(response.body)).to include({
      article: { id: 1, name: 'タイトル', body: '本文' }
    }.as_json)
  end

まとめ

超簡単にですがRails APIのrequest specの書き方をまとめました
あとは paramsitの中身を変えるだけで応用できるかなと思います
間違いなどあればコメントで指摘していただけますと幸いです!

参考記事

3
2
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
3
2