LoginSignup
9
8

More than 3 years have passed since last update.

【Rails】Rspecでマクロを定義して処理を共通化する方法

Last updated at Posted at 2020-07-13

目標

ログイン処理を共通化する。

開発環境

・Ruby: 2.5.7
・Rails: 5.2.4
・rspec-rails: 4.0.1
・Vagrant: 2.2.7
・VirtualBox: 6.1
・OS: macOS Catalina

実装

1.supportディレクトリを作成

$ mkdir support

2.supportディレクトリ内にファイルを作成し、編集

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

3.rails_helper.rbを編集

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

RSpec.configure do |config|
  config.include LoginMacros # 追記
end

【解説】

supportディレクトリを読み込む。

Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }

2で定義したモジュールを使用できるようにする。

config.include LoginMacros

4.メソッドを使用する

require 'rails_helper'

RSpec.describe '認証のテスト', type: :feature do
  let(:user) { create(:user) }
  subject { page }

  describe 'ユーザー認証のテスト' do
    context 'ユーザーログインのテスト' do
      it 'ログインできること' do
        visit new_user_session_path
        login(user) # メソッドを使用
        is_expected.to have_content 'ログアウト'
      end
    end
  end
end
9
8
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
9
8