Skip to content

Instantly share code, notes, and snippets.

@cczona
Forked from chumpy/capybara_cheat_sheet.md
Created December 17, 2012 06:04
Show Gist options
  • Save cczona/4316122 to your computer and use it in GitHub Desktop.
Save cczona/4316122 to your computer and use it in GitHub Desktop.

Capybara Cheat Sheet

Navigating

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

Clicking links and buttons

  click_link('id-of-link')
  click_link('Link Text')
  click_button('Save')
  click('Link Text') # Click either a link or a button
  click('Button Value')

Interacting with forms

  fill_in('First Name', :with => 'John')
  fill_in('Password', :with => 'Seekrit')
  fill_in('Description', :with => 'Really Long Text…')
  choose('A Radio Button')
  check('A Checkbox')
  uncheck('A Checkbox')
  attach_file('Image', '/path/to/image.jpg')
  select('Option', :from => 'Select Box')
  unselect('Option', :from => 'Select Box')

Scoping

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

Querying

Note these have corresponding versions of has_no_*.

  page.has_xpath?('//table/tr')
  page.has_css?('table tr.foo')
  page.has_content?('foo')
  page.has_link?
  page.has_button?("Update")
  page.has_field?
  page.has_checked_field?
  page.has_unchecked_field?
  page.has_table?
  page.has_select?

Each also has corresponding matchers:

  page.should have_*
  page.should have_no_*

Finding

  find('ul li').text
  find_field('First Name').value
  find_link('Hello').visible?
  find_button('Send').click
  find_by_id('sidebar')
  find('//table/tr').click
  locate("//*[@id='overlay'").find("//h1").click
  all('a').each { |a| a[:href] }

Scripting

  result = page.evaluate_script('4 + 4');

Debugging

  save_and_open_page

Asynchronous JavaScript

  it "should do this thing that's generated via JS", js: true do...end
  click_link('foo')
  click_link('bar')
  page.should have_content('baz')
  page.should_not have_xpath('//a')
  page.should have_no_xpath('//a')

Scoping

  within(:css, 'ul li') { ... }
  find(:css, 'ul li').text
  locate(:css, 'input#name').value
  Capybara.default_selector = :css
  within('ul li') { ... }
  locate('input#name').value
  scope_to

Miscellaneous

  all
  body
  current_url
  drag
  field_labeled
  source
  wait_until
  current_path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment