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

【備忘録】Request SpecでAPIのレスポンスをテストする方法

0
Posted at

はじめに

書籍APIのアプリを作成している際、コントローラの動作をテストする一つである、RSpecのRequest Specの書き方ついて学んだので、その備忘録として投稿します。

参考にした記事はこちら。

Request Specとは

Request Specは

HTTPリクエスト → Rails → レスポンス

という APIの一連の流れをテストするものです。

つまり

routing
controller
response(JSON)

をまとめて検証できます。

今回テストするAPI

例として、以下のAPIを想定します。

メソッド エンドポイント 内容
GET /api/v1/books 書籍一覧取得
GET /api/v1/books/:slug 書籍詳細取得

specファイルの作成

Request Specは以下の場所に作成します。

spec/requests/books_spec.rb

基本構造

まずはRSpecの基本構造です。

require "rails_helper"

RSpec.describe "Api::V1::Books", type: :request do
end

ポイントはここです。

type: :request

これを書くことで

get
post
patch
delete

などの HTTPリクエストメソッドが使えるようになります。

GET /api/v1/books のテスト

まずはGETリクエストで一覧を取得できることを確認します。

describe "GET /api/v1/books" do
  context "when books exist" do
    let!(:book) do
      Book.create!(
        name: "Sample Book",
        slug: "sample-book",
        position: 1,
        total_chapters: 10
      )
    end

    it "returns books" do
      get "/api/v1/books"

      expect(response).to have_http_status(:ok)

      json = JSON.parse(response.body)
      expect(json.first["slug"]).to eq("sample-book")
    end
  end
end

APIリクエスト

get "/api/v1/books"

Request Specではこのように実際のAPIエンドポイントにリクエストを送ります。

ステータスコードの確認

expect(response).to have_http_status(:ok)

これはHTTP 200 OKが返っているかを確認しています。

シンボルで書くことが多いです。

シンボル ステータス
:ok 200
:not_found 404
:created 201

JSONレスポンスの確認

json = JSON.parse(response.body)

APIのレスポンスは JSON文字列なのでStringからHashに変換します。

[
  {
    "slug": "sample-book"
  }
]

これを

json.first["slug"]

で取り出して検証します。

GET /api/v1/books/:slug のテスト

次に詳細取得APIのテストです。

describe "GET /api/v1/books/:slug" do
  context "when the book exists" do
    let!(:book) do
      Book.create!(
        name: "Sample Book",
        slug: "sample-book",
        position: 1,
        total_chapters: 10
      )
    end

    it "returns the book" do
      get "/api/v1/books/sample-book"

      expect(response).to have_http_status(:ok)

      json = JSON.parse(response.body)
      expect(json["slug"]).to eq("sample-book")
    end
  end
end

存在しないデータのテスト

APIでは、存在しないデータのケースもテストしておくことが重要です。

context "when the book does not exist" do
  it "returns 404 error" do
    get "/api/v1/books/sample-book"

    expect(response).to have_http_status(:not_found)
  end
end

これにより
存在しないリソース → 404
というAPI仕様を保証できます。

Request Specを書くメリット

Request Specを書くことで

routing
controller
response

がまとめてテストできます。
そのためAPIが正しく動作するかを実際のリクエストに近い形で検証できます。

まとめ

Request Specでは以下を意識すると書きやすくなります。

  • type: :requestを指定する
  • get でAPIを実行する
  • responseでステータスコードを確認
  • JSON.parseでレスポンスを検証
  • 存在しないケース(404)もテストする
0
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
0
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?