Rails4 rspecとFactoryGirlを用いたdeviseでサインインした状態でのコントローラのテスト

サインインをdeviseを用いて実装している。
サインイン必須のコントローラのテストをおこなうときに、サインイン状態を作るのに少し手間取ったのでメモ。


spec\spec_helper.rbに下記のように記載

RSpec.configure do |config|
  … 
  config.include Devise::TestHelpers, type: :controller # これを追加
end


spec\factories\user.rbに下記のように記載

FactoryGirl.define do
  factory :user do
    email "user@test.com"
    password "userpassword"
    password_confirmation "userpassword"
  end
end


コントローラのテストでは、下記のようにサインインやサインアウトをおこなう

before do
  # ユーザー作成
  @user = create(:user)
    
  # サインイン
  sign_in @user
end
  
after do
  # サインアウト
  sign_out @user
end


参考:
plataformatec/devise · GitHub
Railsのユーザ認証deviseを用いた簡単かつ突っ込んだ実装 - ema25の日記