Skip to content

Instantly share code, notes, and snippets.

@stereosupersonic
Forked from lee-dohm/Capybara Cheat Sheet.md
Last active December 24, 2015 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stereosupersonic/6775739 to your computer and use it in GitHub Desktop.
Save stereosupersonic/6775739 to your computer and use it in GitHub Desktop.

Capybara Cheat Sheet

Navigating

visit('/projects')
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…')
find('#people_search_last_name').set('Huber')

choose('A Radio Button')
check('A Checkbox')
# Check
find(:css, "#cityID").set(true)
# Uncheck
find(:css, "#cityID").set(false)
uncheck('A Checkbox')
attach_file('Image', '/path/to/image.jpg')
select('Option', :from => 'Select Box')
select('Anruf',  :from => 'people_search_activity_character') # people_search_activity_character is the id of the 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

page.has_css?('table tr.foo')
page.has_css?('nav[data-role="primary-navigation"] li', text: 'FAQ')
page.has_content?('foo')
page.has_xpath?('//table/tr')

page.all("ol li").count.should == 2 

page.should have_css('table tr.foo')
page.should have_content('foo')
page.should have_no_content('foo')
page.should have_xpath('//table/tr')

within('footer') { expect(page).to have_content('Copyright') }

find_field('First Name').value
find_link('Hello').visible?
find_button('Send').click
find('//table/tr').click

all('a').each { |a| a[:href] }
first('a').click

Scripting

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

Debugging

save_and_open_page
puts page.html}
File.open("test_#{Time.now.to_i}.html", 'w') { |f| f << page.html}
page.driver.render("test_#{Time.now.to_i}.png",:full => true)

Asynchronous JavaScript

find('input[name="post[title]"]').trigger('focus') #allows triggering of custom events. Works with Javascript drivers

click_link('foo')
click_link('bar')
page.should have_content('baz')
page.should_not have_xpath('//a')
page.should have_no_xpath('//a')

XPath and CSS

within(:css, 'ul li') { ... }
page.first(:link, "Agree").click
page.all("h3.r a").each { ... }
find(:css, 'ul li').text
locate(:css, 'input#name').value
Capybara.default_selector = :css
within('ul li') { ... }
find('ul li').text
locate('input#name').value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment