LoginSignup
1
1

More than 1 year has passed since last update.

RSpecでCookies(永続ログイン)のテストをする方法

Last updated at Posted at 2021-06-24

#「show_me_the_cookies」をインストールする

詳細はこちらを参照してください。

Capybaraの統合テストでブラウザのCookiesを扱うメソッドがいくつか用意されています。

  # puts a string summary of the cookie
  show_me_the_cookie(cookie_name)

  # returns a hash of the cookie
  # form: {:name, :domain, :value, :expires, :path}
  get_me_the_cookie(cookie_name)

  # puts a string summary of all cookies
  show_me_the_cookies

  # returns an array of cookie hashes
  # form: [{:name, :domain, :value, :expires, :path, :secure}]
  get_me_the_cookies

  # deletes the named cookie
  delete_cookie(cookie_name)

  # removes session cookies and expired persistent cookies
  expire_cookies

  # creates a cookie
  create_cookie(cookie_name, cookie_value)

  # creates a cookie for the path or domain
  create_cookie(cookie_name, cookie_value, :path => "...", :domain => "...")

早速インストールしていきます。

Gemfile
group :test do
 gem "show_me_the_cookies"
end
% bundle install

spec/rails_helper.rbに下記を追加します。

spec/rails_helper.rb
RSpec.configure do |config|
  config.include ShowMeTheCookies, :type => :system #Feature Specの場合は「:feature]
end

これで準備完了です!

テストコードを記述する

筆者はFactoryBotを使用しています。

spec/users_login_spec/rb
RSpec.describe 'ユーザーログインテスト', type: :system do
  let(:user) { FactoryBot.create(:user) }

   describe 'ログイン状態の保持のテスト' do
      it '「ログイン状態を保持する」を選択してログインする' do
        visit login_path
        fill_in 'session[email]', with: user.email
        fill_in 'session[password]', with: user.password
        check 'ログイン状態を保持する'
        find('#login-btn').click
        expect(get_me_the_cookie('remember_token')).not_to eq nil
      end

      it '「ログイン状態を保持する」を選択しないでログインする' do
        visit login_path
        fill_in 'session[email]', with: user.email
        fill_in 'session[password]', with: user.password
        find('#login-btn').click
        expect(get_me_the_cookie('remember_token')).to eq nil
      end
   end
end

これで無事に永続ログインのテストができました!

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