This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Capybara Ruby Integration Testing Cheat Sheet

A quick reference guide for Capybara: page navigation, form interactions, RSpec matchers, finders, scoping, modal dialogs, and test debugging.

· Published

Capybara helps you test web applications by simulating how a real user would interact with your app in integration specs.

Navigation & Actions

visit '/login'
visit articles_path

Clicking Links & Buttons

click_on 'Submit'           # Matches link or button text
click_button 'Save Changes'
click_link 'Log Out'

Form Controls

fill_in 'Email', with: '[email protected]'
fill_in 'Password', with: 'secret'

choose 'Male'               # Radio button
check 'Accept Terms'        # Checkbox
uncheck 'Send Newsletter'

select 'California', from: 'State'
unselect 'Hawaii', from: 'State'

attach_file 'Avatar', '/path/to/image.png'

Scoping & Context

Limit actions to a specific DOM node or form:

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 Matchers

expect(page).to have_content('Welcome Back')
expect(page).to have_current_path('/dashboard')

# Element presence
expect(page).to have_selector('div.alert', text: 'Success')
expect(page).to have_css('button.primary')
expect(page).to have_xpath('//table/tr')

# Form controls
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')

# Negative assertions
expect(page).to have_no_content('Error')
expect(page).not_to have_selector('.modal')

Query 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

JavaScript Alerts & Modals

# Accept native browser alert
accept_alert do
  click_button 'Show Alert'
end

# Accept confirmation modal
accept_confirm do
  click_button 'Delete Account'
end

# Dismiss confirmation modal
dismiss_confirm do
  click_button 'Cancel Order'
end

Debugging

# Open rendered HTML page in browser
save_and_open_page

# Save snapshot screenshot (with headless Chrome / Selenium)
save_and_open_screenshot

# Execute JavaScript
page.execute_script("$('.dropdown').show()")
result = page.evaluate_script("window.innerWidth")

Related topics