LoginSignup
0
1

More than 3 years have passed since last update.

【rspec】APIモードで404 Not Foundをjsonで返す時のテストについて

Last updated at Posted at 2019-02-18

APIモードで404 Not Foundをjsonで返す時のテストについて

存在しないプロジェクトのページにアクセスしたら、404 not foundのページを返すテストを書いていた。

しかし、今回はAPI仕様なのでhtmlで404を返してはいけない。

そのため、「APIモードでは、存在しないprojectにアクセスしてきたら、status404を返すだけで良い」という結論。

そもそも論だった。

expect(response).to have_http_status :not_found

もしくは、

expect(response.status).to be 404

というテストを書くだけで良い!(この2つは同義)

have_http_statusは、rspecのマッチャー。(eq等と同じ)
https://www.masalog.site/entry/2018/07/26/214211

このhave_http_statusにHTTPステータスを引数(シンボル)で渡せば、引数のステータスが返せる。

HTTPステータスコード一覧
https://blog.toshimaru.net/rails-http-status-symbols/

success

:okは200番

client error

:not_foundは404番

server error

:internal_server_errorは500番

そしてこの2つは同義。

expect(response).to have_http_status :ok
expect(response.status).to be 200
0
1
1

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