LoginSignup
3
1

More than 1 year has passed since last update.

【Rspec】ログイン機能をモジュールで共通化しテストコードをDRYにする

Posted at

手順

1.rails_helperを編集
2.supportディレクトリにてファイルを作成
3.login機能の記入
4.メソッド使用例

1.rails_helperを編集

rails_helper.rb
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }
# 23行目のコメントアウトを外す

---省略---

RSpec.configure do |config|
  # 中略
  config.include LoginSupport
end

('spec', 'support', '**', '*.rb')
spec/support/◯◯/△△.rbのファイルを読み込むという設定。

RSpec.configure do |config|下に作成したファイルを読み込むという記述をする。
今回はLoginSupportと命名してモジュールを作成する。

2.supportディレクトリにてファイルを作成

手順1でsupportディレクトリ下を読み込むという設定をしたので、supportディレクトリを作成。

次に、ファイルを作成するが、その際の注意としてファイル名とモジュール名は一致させる必要がある。

ターミナル.
$ mkdir support
#ディレクトリ作成

$ touch spec/support/login_support.rb
#ファイル作成

3.login機能の記入

spec/support/login_support.rb
module LoginSupport
  def login(user)
    fill_in 'メールアドレス', with: user.email
    fill_in 'パスワード', with: user.password
    click_button 'ログイン'
  end
end

4.メソッド使用例

user_sessions_spec.rb
require 'rails_helper'

RSpec.describe 'UserSessions', type: :system do
  let(:user) { create(:user) }

  describe 'ログイン' do
    context 'フォームの入力値が正常' do
      it 'ログイン処理が成功する' do
        login(user)
        expect(page).to have_content 'Login successful'
        expect(current_path).to eq root_path
      end
    end
  end
end

参考記事

【Rails】Rspecでマクロを定義して処理を共通化する方法
Rspecでサインインメソッドを共通化して切り出す(devise使わないとき)[system spec][request spec]

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