Capybara Capybara は、実際のユーザーがブラウザを操作する振る舞いをシミュレートし、Ruby アプリケーションの統合テスト・E2Eテストを実行するライブラリです。
ページ遷移とアクション
visit '/login'
visit articles_path
リンクやボタンのクリック
click_on 'Submit' # リンクまたはボタンのテキストに一致
click_button 'Save Changes'
click_link 'Log Out'
フォーム要素の入力操作
fill_in 'Email', with: '[email protected]'
fill_in 'Password', with: 'secret'
choose 'Male' # ラジオボタンを選択
check 'Accept Terms' # チェックボックスをオン
uncheck 'Send Newsletter'
select 'California', from: 'State'
unselect 'Hawaii', from: 'State'
attach_file 'Avatar', '/path/to/image.png'
スコープ制限(特定のDOM領域)
特定のエレメントやフォームの内部に探索スコープを絞り込みます:
within '.modal-dialog' do
fill_in 'Username', with: 'admin'
click_button 'Confirm'
end
within_fieldset 'Shipping Address' do
fill_in 'City', with: 'San Francisco'
end
within_table 'Orders' do
expect(page).to have_content('$99.00')
end
RSpec マッチャー構文
expect(page).to have_content('Welcome Back')
expect(page).to have_current_path('/dashboard')
# 要素の存在チェック
expect(page).to have_selector('div.alert', text: 'Success')
expect(page).to have_css('button.primary')
expect(page).to have_xpath('//table/tr')
# フォームコントロールの状態検証
expect(page).to have_field('First Name', with: 'John')
expect(page).to have_checked_field('Agree to Terms')
expect(page).to have_select('Role', selected: 'Developer')
expect(page).to have_button('Submit', disabled: false)
expect(page).to have_link('Profile', href: '/users/1')
# 要素が存在しないことの検証(否定アサーション)
expect(page).to have_no_content('Error')
expect(page).not_to have_selector('.modal')
DOM 要素ファインダー
btn = find('button.submit')
btn.click
field = find_field('Email')
link = find_link('Home')
all('li.nav-item').each do |item|
puts item.text
end
JavaScript ダイアログとアラート
# ブラウザ標準のアラートを承認
accept_alert do
click_button 'Show Alert'
end
# 確認ダイアログの「OK」をクリック
accept_confirm do
click_button 'Delete Account'
end
# 確認ダイアログの「キャンセル」をクリック
dismiss_confirm do
click_button 'Cancel Order'
end
テストデバッグ手法
# 現在のレンダリング済みHTMLをブラウザで開く
save_and_open_page
# 現在の画面スクリーンショットを保存
save_and_open_screenshot
# ブラウザ上で任意のJavaScriptを実行
page.execute_script("$('.dropdown').show()")
result = page.evaluate_script("window.innerWidth")