0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails初学者】結合テスト:ログイン機能のテストコードとCapybaraメソッド解説

Posted at

🧪 Rails結合テスト:ログイン機能のテストコードとCapybaraメソッド解説

こんにちは!Rails初学者として、今日は結合テストについて学習しました。特に、ログイン機能のテストコードを通じて、Capybaraのさまざまなメソッドを使用しました。以下に、実際に記述したコードと各メソッドの解説をまとめます。


✅ ログインが成功する場合のテスト

context 'ログインができるとき' do
  it '保存されているユーザーの情報と合致すればログインができる' do
    visit root_path
    expect(page).to have_content('ログイン')
    visit new_user_session_path
    fill_in 'Email', with: @user.email
    fill_in 'Password', with: @user.password
    find('input[name="commit"]').click
    expect(page).to have_current_path(root_path)
    expect(find('.user_nav').find('span').hover).to have_content('ログアウト')
    expect(page).to have_no_content('新規登録')
    expect(page).to have_no_content('ログイン')
  end
end

❌ ログインが失敗する場合のテスト

context 'ログインができないとき' do
  it '保存されているユーザーの情報と合致しないとログインができない' do
    visit root_path
    expect(page).to have_content('ログイン')
    visit new_user_session_path
    fill_in 'Email', with: ''
    fill_in 'Password', with: ''
    find('input[name="commit"]').click
    expect(page).to have_current_path(new_user_session_path)
  end
end

🛠️ 使用したCapybaraメソッドの解説

メソッド 説明
visit 指定したパスにアクセスします。例:visit root_pathでトップページに移動します。
expect(page).to have_content('文字列') ページ内に指定した文字列が含まれていることを確認します。
fill_in 'フィールド名', with: 値 フォームの入力フィールドに値を入力します。
find('セレクタ') 指定したセレクタに一致する要素を探します。
click ボタンやリンクなどの要素をクリックします。
have_current_path(パス) 現在のページのパスが指定したパスと一致することを確認します。
hover 要素にマウスオーバー(ホバー)します。
have_no_content('文字列') ページ内に指定した文字列が含まれていないことを確認します。

🧠 学んだことのまとめ

・Capybaraを使用することで、ユーザーの操作をシミュレートしたテストが可能になります。

・visitやfill_in、clickなどのメソッドを組み合わせて、実際のユーザーの操作を再現できます。

・expectを使用して、ページの状態や表示内容を検証できます。

・テストコードを通じて、アプリケーションの挙動を確認し、バグの早期発見につなげることができます。

以上、今日の学習記録でした!引き続き、Railsの学習を進めていきます。🚀

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?