Skip to content

Instantly share code, notes, and snippets.

@knubie
Created October 13, 2014 22:20
Show Gist options
  • Save knubie/62b847edd670ccc11050 to your computer and use it in GitHub Desktop.
Save knubie/62b847edd670ccc11050 to your computer and use it in GitHub Desktop.
# Credit: http://richardconroy.blogspot.com/2010/08/capybara-reference.html
#Navigating
visit('/projects')
#Clicking links and buttons
click_link('id-of-link') # e.g. <a href="google.com" id="id-of-link">click me</a>
click_link('Link Text') # e.g. <a href="google.com">Link Text</a>
click_button('Save')
click('Link Text') # Click either a link or a button
click('Button Value')
#Interacting with forms
# First parameter can either be it's ID, label text, or name.
fill_in('Label Name', :with => 'John') # e.g. <label>First Name <input name="foo"></label>
fill_in('input_name', :with => 'foo') # e.g. <input name="input_name">
fill_in('input_id', :with => 'foo') # e.g. <input id="input_id">
choose('A Radio Button')
check('A Checkbox')
uncheck('A Checkbox')
attach_file('Image', '/path/to/image.jpg')
select('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
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')
find_field('First Name').value
find_link('Hello').visible?
find_button('Send').click
find('//table/tr').click
locate("//*[@id='overlay'").find("//h1").click
all('a').each { |a| a[:href] }
#Screenshots
# Screenshots will be saved relative to the directory(folder) that rspec is run from.
# Assuming rspec is run from Documents/essie :
page.save_screenshot('homepage.png') # -> will be saved to Documents/essie/foobar.png
page.save_screenshot('screenshots/homepage.png') # -> Documents/essie/screenshots/foobar.png
# this is true regardless of where the actual test.rb file is located.
#Scripting
result = page.evaluate_script('4 + 4');
#Debugging
save_and_open_page
#Asynchronous JavaScript
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') { ... }
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