3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【RSpec】JSONの値を確認するテスト

Posted at

##環境
Ruby 3.0.2
Rails 6.1.4.1

##APIのリクエストテスト
gemを使わずにjsonが期待通りに取れているかのテストを書くとこうなる。

describe "GET /api/v1/fruits" do
    subject { get '/api/v1/fruits', headers: headers }
    let!(:available_fruits1) { create(:fruit) }
    let!(:available_fruits2) { create(:fruit) }
    let!(:unavailable_fruits) { create(:fruit, :unavailable) }

  it '旬の果物を返すこと' do
    subject
    json = JSON.parse(response.body)
    expect(response.status).to eq 200

    # 果物が3つあり、そのうち旬の果物が2つ、旬じゃないのが1つ。jsonで取れるのは果物が2つ
    expect(json['fruits'].length).to eq 2

    # 旬の果物の2つは含まれているか
    expect(json['fruits'][0]).to include({"id"=>available_fruits1.id})
    expect(json['fruits'][1]).to include({"id"=>available_fruits2.id})

    # 旬でない果物は含まれていないか
    expect(json['fruits'][0]).not_to include({"id"=>unavailable_fruits.id})
    expect(json['fruits'][1]).not_to include({"id"=>unavailable_fruits.id})
  end
end

##参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?