Controller specs
コントローラ仕様書はtype: :controller
を印付けるまたはspec/controllers
内のspecを置くことでconfig.infer_spec_type_from_file_location!
を設定した場合に印づける
Controller specs are marked by type: :controller or if you have set config.infer_spec_type_from_file_location! by placing them in spec/controllers.
コントローラ仕様書はrailsの機能テスト(ActionController::TestCase::Behavior)に対してRSpecのラッパーです。各例でシングルhttpリクエストの模擬を行い、その時の期待された次のような出力を明示する。
A controller spec is an RSpec wrapper for a Rails functional test (ActionController::TestCase::Behavior). It allows you to simulate a single http request in each example, and then specify expected outcomes such as:
レンダリングされたテンプレート
- rendered templates
リダイレクト
- redirects
ビューと共有されたコントローラ内で割り当てられたインスタンス変数
- instance variables assigned in the controller to be shared with the view
レスポンスと一緒に送り返されたcookie
- cookies sent back with the response
出力を指定するには、(下のやつ)使うことができる
To specify outcomes, you can use:
標準的RSpecマッチャー
- standard rspec matchers (expect(response.status).to eq(200))
標準test/unit
のアサーション(主張)
- standard test/unit assertions (assert_equal 200, response.status)
railsのアサーション
- rails assertions (assert_response 200)
railsの具体的マッチャー
- rails-specific matchers:
render_template
expect(response).to render_template(:new) # wraps assert_template
redirect_to
expect(response).to redirect_to(location) # wraps assert_redirected_to
have_http_status
expect(response).to have_http_status(:created)
be_a_new
expect(assigns(:widget)).to be_a_new(Widget)
Examples
RSpec.describe TeamsController do
describe "GET index" do # indexアクションをする
it "assigns @teams" do # @teamsに割り当てられたか
team = Team.create # モデルを保存させる
get :index # indexアクションでページを取得させる
expect(assigns(:teams)).to eq([team]) # (assigns(:teams)と[team]が等しい値か?
end
it "renders the index template" do # インデックステンプレートをレンダリングする
get :index # indexアクションに対してgetリクエストをする
expect(response).to render_template("index") # 変数responseとrender_template("index")になったか?
end
end
end
Views
初期値によって、ビューはレンダリングされない。詳細のためにスタブ化されたビュー(リンク)とrender_views(リンク)を見て下さい
by default, views are not rendered. See views are stubbed by default and render_views for details.
Headers
コールでヘッダーを設定したい場合、リクエストスペックを使うことを薦めます。今まで通りカスタムhttpヘッダー付きのコントローラスペックを使いたいならば、request.headers
を使える
We encourage you to use request specs if you want to set headers in your call. If you still want to use controller specs with custom http headers you can use request.headers:
require "rails_helper"
RSpec.describe TeamsController, type: :controller do
describe "GET index" do #
it "returns a 200" do # 200番が返ってきて欲しい
request.headers["Authorization"] = "foo"
get :show
expect(response).to have_http_status(:ok) # have_http_status(:ok)で200番と等しいと考える
end
end
end