サポートモジュール(テストコードをまとめる)

サポートモジュール

テストコード内にて同じ記述を避けるために1つにまとめる。

supportファイルを作成し、その中にこのようなファイルを作る。

spec/support/sign_in_support.rb
1
2
3
4
5
6
7
8
9
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

rails_helper.rb 23行目のコメントアウトを外す。

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

同じくrails_helper内

Rspec.configure内に以下のように追加する。これはファイル名と一緒の名前。

RSpec.configure do |config|
  config.include SignInSupport

 

これでサポートモジュールを使えるようになる。

 

後はテストコード内で

# ログインする
      sign_in(@user)

のように使えばおk。