Spec 結合テストコードをまとめる
同じ処理を繰り返している箇所 →サポートモジュールを使って一つのメソッドにまとめる
ex)ログイン動作 ←何度もやってる
サポートモジュールの作成
spec/support/sign_in_support.rb
module SignInSupport def sign_in(user) visit new_user_session_path fill_in 'Email', with: user.email fill_in 'Password', with: user.password find('input[name="commit"]').click expect(current_path).to eq root_path end end
サポートモジュールを読み込めるようにする
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }
- モジュールを設定
RSpec.configure do |config| config.include SignInSupport #other settings end
テストコードの該当部分をサポートモジュールのメソッドに置き換える
- before
visit new_user_session_path fill_in 'Email', with: user.email fill_in 'Password', with: user.password find('input[name="commit"]').click expect(current_path).to eq root_path
- after
sign_in(@user) #@userはFactoryBotで作ったテストデータ