Capybara O Capybara ajuda você a testar aplicações web simulando como um usuário real interagiria com seu aplicativo em testes de integração.
Navegação e Ações
visit '/login'
visit articles_path
Clicando em links e botões
click_on 'Submit' # Corresponde ao texto do link ou botão
click_button 'Save Changes'
click_link 'Log Out'
Controles de formulário
fill_in 'Email', with: '[email protected]'
fill_in 'Password', with: 'secret'
choose 'Male' # Botão de rádio
check 'Accept Terms' # Caixa de seleção
uncheck 'Send Newsletter'
select 'California', from: 'State'
unselect 'Hawaii', from: 'State'
attach_file 'Avatar', '/path/to/image.png'
Escopo e Contexto (Scoping)
Limite ações a um nó específico do DOM ou formulário:
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
Matchers do RSpec
expect(page).to have_content('Welcome Back')
expect(page).to have_current_path('/dashboard')
# Presença de elementos
expect(page).to have_selector('div.alert', text: 'Success')
expect(page).to have_css('button.primary')
expect(page).to have_xpath('//table/tr')
# Controles de formulário
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')
# Asserções negativas
expect(page).to have_no_content('Error')
expect(page).not_to have_selector('.modal')
Localizadores de elementos (Finders)
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
Alertas e diálogos JavaScript
# Aceitar alerta nativo do navegador
accept_alert do
click_button 'Show Alert'
end
# Aceitar modal de confirmação
accept_confirm do
click_button 'Delete Account'
end
# Recusar modal de confirmação
dismiss_confirm do
click_button 'Cancel Order'
end
Depuração (Debugging)
# Abrir página HTML renderizada no navegador
save_and_open_page
# Salvar captura de tela
save_and_open_screenshot
# Executar JavaScript
page.execute_script("$('.dropdown').show()")
result = page.evaluate_script("window.innerWidth")