LoginSignup
2
3

More than 5 years have passed since last update.

rspecでDeviseのログイン機能を使用する方法

Posted at

概要

Webサービスのログイン処理にDevise使用しています。その際、ログイン後の処理をrspecでテストするためにどうすればよいか分からなかったため、調査した結果を記載します。

手順

参考にしたサイト

① 事前準備をする。

spec/rails_helper.rb
・・・
include Warden::Test::Helpers
・・・
Rspec.configure do |config|
  ・・・
  config.include Warden::Test::Helpers
  ・・・
end

② FactoryGirlでテスト用のモデルを作成する。

spec/factories/user.rb
FactoryGirl.define do
  factory :user do
    email "admin@gmail.com"
    password "1234567"
  end
end

login_asを使用して、テストを行う。

spec/requests/management_spec.rb
require 'rails_helper'

describe "management" do
  let(:user){ create(:user) }
  context "Get admin_path" do
    it "Response is 200." do
      # ログインする。
      login_as(user)

      get admin_path
      expect(response).to have_http_status(200) 
    end
  end
end

2
3
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
2
3