0
0

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(コントローラーの単体テスト)

Last updated at Posted at 2021-05-05

コントローラーの単体テストコードを書く方針

コントローラーのテストコードを書く方針は、あるアクションにリクエストを送ったときに想定通りのレスポンスが生成されるかどうかを確かめることです。

今回は、以下のexampleをテストしました。

  • indexアクションにリクエストすると正常にレスポンスが返ってくる
describe 'GET #index' do
 it 'indexアクションにリクエストすると正常にレスポンスが返ってくる' do
  get root_path
  expect(response.status).to eq 200
 end
end

まず最初にどこのパスにリクエストを送りたいか記述します。(rails routesにてパスを確認しました。)

Prefix          Verb    URIPattern                    Controller#Action
root            GET     /                             tweets#index

今回は、indexアクションにリクエストを送りたいのでget root_pathです。

次の行のresponseの記述でリクエストに対するレスポンスそのものが含まれます。続けて.statusと記述することでそのレスポンスのステータスコードが取得できます。

ステータスコードは以下のような分類になっています。

HTTPステータスコード
100~ 処理の継続中
200~ 処理の成功
300~ リダイレクト
400~ クライアントのエラー
500~ サーバーのエラー

今回は正常にレスポンスを得ることを確かめたいため200というステータスコードを期待します。よって、expect(response.status).to eq 200と記述しました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?