Capybara

Table of Contents

Visit a specific route in your web app. If using rails, you can specify a path.

visit('/projects')
visit(post_comments_path(post))

Find a link or button by the given parameter and click it.

click_link('id-of-link')
click_link('Link Text')
click('Link/Button Text')
click_button('Save')
click_on('Button Value')
find('form.foo .btn').click

Interacting with forms

  • Text Boxes
fill_in('First Name', :with => 'John')
  • Radio Buttons
choose('A Radio Button')
choose("radio_group_selector"), option: "Option 5"
  • Check Boxes
check('A Checkbox')
uncheck('A Checkbox')
  • Attach files
attach_file('Image', '/path/to/image.jpg')
  • Select Options
select('Option', :from => 'Select Box')
unselect('Option', from: select_box)
find("#select_id").select("value")

Scoping

Interact with an object nested in other

within(:xpath, "//li[@id='employee']") { fill_in 'Name', :with => 'Jimmy' }
within("li#employee") { fill_in 'Name', :with => 'Jimmy' }
within_fieldset('Employee') { fill_in 'Name', :with => 'Jimmy' }
within_table('Employee') { fill_in 'Name', :with => 'Jimmy' }

Querying

Check whether the page or field includes a given element

page.has_xpath?('//table/tr')
page.has_css?('table tr.foo')
page.has_content?('foo')
page.should have_xpath('//table/tr')
page.should have_css('table tr.foo')
page.should have_content('foo')
page.should have_no_content('foo')
expect(page).to have_selector 'foobar'
find_field('First Name').value
find_link('Hello').visible? #false, finds only visible
find_button('Send').click
find('//table/tr').click
all('a').each { |a| a[:href] }

Find element, take an action

find("input.file").attach_file
find("input.checkbox").check
find("input.select").choose
find(".button").click_button
find(".link").click_link
find(".link").click_link_or_button
find(".link").click_on
find(".link").click
find("input.text").set('Jimmy') #instead of fill_in
find("input.select").select
find("input.checkbox").uncheck
find("input.select").unselect
find("input.select").unselect_option(option: "Option 5")
find("input.checkbox").checked?
find(".button").disabled?
find(".link").hover
find("input.select").selected?
find("input.text").value
find(".text").text
find(".link").visible?

Scripting

result = page.evaluate_script('4 + 4')
periods = page.evaluate_script("$('#MainContent_dd').map(function() { return $(this).text() }).get()")

Debugging

save_and_open_page
screenshot_and_open_image # capybara-screenshot gem

Asynchronous JS

click_link('foo')
click_link('bar')
page.should have_content('baz')
page.should_not have_xpath('//a')
page.should have_no_xpath('//a')
using_wait_time 5 { # assertions }