- 更新日: 2013年11月22日
- RSpec
RSpec + Capybaraでセッション管理コントローラーに直接HTTPリクエストを発行してテスト
Rails アプリのユーザー認証で使うセッションコントローラーにおける RSpec + Capybara でのテスト。
すでにサインインしているユーザーには、サインインページを再度表示しない、サインインのリクエストを直接発行させない、というロジックにしたい。
具体的には、サインイン済みのユーザーがサインインページ(サインイン用のフォーム)を表示させようとしたら、ルートパスへとリダイレクトさせる。HTTPによる直接のサインインのリクエストに対しても、ルートパスへとリダイレクトさせる。
テストコード spec/requests/authentication_pages_spec.rb
テストのために以下のコードを書きました。get, post メソッドを使って、SessionsController のアクション(new, create)に対し HTTP リクエストを直接発行させます。フォームを使わないリクエストに対しても万全にするため。
spec/requests/authentication_pages_spec.rb
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | describe "AuthenticationPages" do   describe "authorization" do     describe "for signed-in users" do       let(:user) { FactoryGirl.create(:user) }       before { sign_in user, no_capybara: true }       describe "in the Sessions controller" do         describe "using a 'new' action" do           before { get new_session_path }           specify { expect(response).to redirect_to(root_path) }         end         describe "using a 'create' action" do           # ここ書き方が怪しい           before { post sessions_path, email: user.email, password: user.password }           specify { expect(response).to redirect_to(root_path) }         end       end     end   end end | 
テスト実行。
| 1 2 3 | bundle exec rspec spec/ | 
テストを通らない赤色が2つ出ます、specify の行のところです。
実装 app/controllers/sessions_controller.rb
テストを通すために、SessionsController に no_signed_in_user メソッドを実装して before_action に登録しました。
app/controllers/sessions_controller.rb
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class SessionsController < ApplicationController   before_action :no_signed_in_user, only: [:new, :create]   def new   end   def create     ...   end   def destroy     ...   end   private     def no_signed_in_user       redirect_to root_path if signed_in?     end end | 
セッションコントローラーの new, create アクションにはサインインしていないユーザーのみ、アクセスできるようにする。サインイン済みのユーザーは、redirect_to root_path でルートへとリダイレクトさせます。
これでテストを通って、狙い通りの挙動となりましたが、いまいち RSpec の書き方に自信が持てない(苦笑。テストの18行目、before { post sessions_path, email: user.email, password: user.password } の行のところが特に。これであってますかね。
Ruby on Rails Tutorial を参考にしつつウェブアプリケーションを製作中なのですが、なんとなく RSpec のテストの書き方に慣れて、テストを書くのが楽しくなってきました。
- RSpec の関連記事
- FactoryGirlをSpringと共に使う時の注意
- 複数モデルのpost :createをテストするRSpecコード(Controller Spec)
- RSpec3でTime.nowをスタブ化(stub)
- RSpecでJSONによるPOSTリクエストをテスト
- RSpec & Capybara の雑感
- RSpec+Capybaraで同名の複数要素の並び順をテストする
- RSpec3ではrails_helper.rbがrequireされる
- Capybara + Launchy で RSpec テストをブラウザで確認
- CapybaraのwithinをRSpecで使う
- Serverspec(RSpec)のテスト出力に色を付けて見やすくフォーマット

 画像付き英語辞書 Imagict | 英単語をイメージで暗記
画像付き英語辞書 Imagict | 英単語をイメージで暗記









Leave Your Message!