SlideShare a Scribd company logo
Capybara
Exemplos de configuração
Com cucumber sem Rails
require 'capybara/cucumber'
Capybara.app = MyRackApp
Com cucumber-rails
rails generate cucumber:install --
capybara
Nos steps do cucumber
When /I sign in/ do
within("#session") do
fill_in 'Login', :with =>
'user@example.com'
fill_in 'Password', :with => 'password'
end
click_link 'Sign in'
end
Tags para uso de JS
@javascript
Scenario: do something Ajaxy
When I click the Ajax link
...
Capybara.javascript_driver = :culerity
Tags disponívels
@javascript
Scenario: do something Ajaxy
When I click the Ajax link
...
@selenium
Scenario: do something Ajaxy
When I click the Ajax link
...
@culerity
Scenario: do something Ajaxy
When I click the Ajax link
...
@rack_test
Scenario: do something Ajaxy
When I click the Ajax link
...
Utilizando com RSpec
require 'capybara/rspec'
describe "the signup process", :type =>
:request do
before :each do
User.make(:email => 'user@example.com',
:password => 'caplin')
end
it "signs me in" do
within("#session") do
fill_in 'Login', :with =>
'user@example.com'
fill_in 'Password', :with => 'password'
end
click_link 'Sign in'
end
end
Habilitando o driver JS
describe 'some stuff which requires js', :js
=> true do
it 'will use the default js driver'
it 'will switch to one specific driver',
:driver => :celerity
end
DSL do Capybara
feature "Signing up" do
background do
User.make(:email => 'user@example.com',
:password => 'caplin')
end
scenario "Signing in with correct
credentials" do
within("#session") do
fill_in 'Login', :with =>
'user@example.com'
fill_in 'Password', :with => 'caplin'
end
click_link 'Sign in'
end
end
Isto é apenas uma forma de utilizar o
RSpec.
feature é um alias para describe ...,
:type => :request
background é um alias para before'
scenario é um alias para it/specify
Junto com Test::Unit
class ActionDispatch::IntegrationTest
include Capybara::DSL
end
Capybara com qualquer aplicação
Rack
Capybara.app = MyRackApp
Selecionando o Driver
Capybara.default_driver = :selenium
Capybara.current_driver = :rack_test # Este é
o padrão se não mudarmos para outro na linha
acima
Capybara.use_default_driver #volta para o
driver padrão
A DSL
Navegando
visit('/projects')
visit(post_comments_path(post))
current_path.should ==
post_comments_path(post)
Clicando em links e botões
click_link('id-of-link')
click_link('Link Text')
click_button('Save')
click_on('Link Text') # clica em um link ou
botão
click_on('Button Value')
Interagindo com formulários
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')
Verificando o conteúdo da página
page.has_selector?('table tr')
page.has_selector?(:xpath, '//table/tr')
page.has_no_selector?(:content)
page.has_xpath?('//table/tr')
page.has_css?('table tr.foo')
page.has_content?('foo')
page.has_text?('foo')
Verificando o conteúdo da página
com RSpec
page.should have_selector('table tr')
page.should have_selector(:xpath,
'//table/tr')
page.should have_no_selector(:content)
page.should have_xpath('//table/tr')
page.should have_css('table tr.foo')
page.should have_text('foo')
page.should have_no_text('foo')
page.html.should match /<span>.../i
Buscando
find_field('First Name').value
find_link('Hello').visible?
find_button('Send').click
find(:xpath, "//table/tr").click
find("#overlay").find("h1").click
all('a').each { |a| a[:href] }
find('#navigation').click_link('Home')
find('#navigation').should have_button('Sign
out')
Definindo escopos
within("li#employee") do
fill_in 'Name', :with => 'Jimmy'
end
within(:xpath, "//li[@id='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
Rodando Javascript
page.execute_script("$('body').empty()")
result = page.evaluate_script('4 + 4');
Debug
save_and_open_page
Mais exemplos
Utilizando a DSL em qualquer lugar
require 'capybara'
require 'capybara/dsl'
Capybara.default_driver = :culerity
module MyModule
include Capybara::DSL
def login!
within("//form[@id='session']") do
fill_in 'Login', :with =>
'user@example.com'
fill_in 'Password', :with => 'password'
end
click_link 'Sign in'
end
end
Chamando servidores remotos
visit('http://www.google.com')
Capybara.current_driver = :selenium
Capybara.app_host = 'http://www.google.com'
...
visit('/')
Capybara sem o servidor Rack
interno
Capybara.run_server = false
Session
require 'capybara'
session = Capybara::Session.new(:culerity,
my_rack_app)
session.within("//form[@id='session']") do
session.fill_in 'Login', :with =>
'user@example.com'
session.fill_in 'Password', :with =>
'password'
end
session.click_link 'Sign in'
Seletores XPath
within(:xpath, '//ul/li') { ... }
find(:xpath, '//ul/li').text
find(:xpath, '//li[contains(.//a[@href =
"#"]/text(), "foo")]').value
Seletores padrão
Capybara.default_selector = :xpath
find('//ul/li').text
Seletores personalizados
Capybara.add_selector(:id) do
xpath { |id|
XPath.descendant[XPath.attr(:id) == id.to_s] }
end
Capybara.add_selector(:row) do
xpath { |num| ".//tbody/tr[#{num}]" }
end
Capybara.add_selector(:flash_type) do
css { |type| "#flash.#{type}" }
end
find(:id, 'post_123')
find(:row, 3)
find(:flash_type, :notice)
Adicionando drivers
Capybara.register_driver :selenium do |app|
Capybara::Selenium::Driver.new(app, :browser
=> :chrome)
end
Capybara.register_driver :selenium_chrome do
|app|
Capybara::Selenium::Driver.new(app, :browser
=> :chrome)
end
Parte do Livro de Rails 3.1 de Rodrigo Urubatan Ferreira Jardim, guia de referência rápida
publicado originalmente em http://www.urubatan.com.br

More Related Content

PPTX
SenchaCon 2016: Want to Use Ext JS Components with Angular 2? Here’s How to I...
PPTX
jQuery for Sharepoint Dev
PDF
How to actually use promises - Jakob Mattsson, FishBrain
PDF
Workshop 18: CSS Animations & cool effects
ODP
Mechanize at the Ruby Drink-up of Sophia, November 2011
PDF
Difference between java script and jquery
PPT
jQuery Performance Rules
PDF
Polymer - pleasant client-side programming with web components
SenchaCon 2016: Want to Use Ext JS Components with Angular 2? Here’s How to I...
jQuery for Sharepoint Dev
How to actually use promises - Jakob Mattsson, FishBrain
Workshop 18: CSS Animations & cool effects
Mechanize at the Ruby Drink-up of Sophia, November 2011
Difference between java script and jquery
jQuery Performance Rules
Polymer - pleasant client-side programming with web components

What's hot (20)

PPTX
Jquery Complete Presentation along with Javascript Basics
PDF
The Future is in Pieces
PPTX
JavaScript and jQuery Basics
PPTX
Ext JS Architecture Best Practices - Mitchell Simeons
KEY
Simple Web Apps With Sinatra
 
PDF
Randomising css animations
PDF
Massimo Artizzu - The tricks of Houdini: a magic wand for the future of CSS -...
PDF
Devoxx 2014-webComponents
PPTX
JavaScript Advanced - Useful methods to power up your code
PPTX
18. images in symfony 4
KEY
jQuery Anti-Patterns for Performance & Compression
DOCX
Borrador del blog
PDF
Angular Directives from Scratch
PDF
Yearning jQuery
PPTX
Site optimization
PDF
Polymer 1.0
PPT
Introduction to JQuery
PPTX
PPTX
Ampersandjs
PPTX
iPhone Web Applications: HTML5, CSS3 & dev tips for iPhone development
Jquery Complete Presentation along with Javascript Basics
The Future is in Pieces
JavaScript and jQuery Basics
Ext JS Architecture Best Practices - Mitchell Simeons
Simple Web Apps With Sinatra
 
Randomising css animations
Massimo Artizzu - The tricks of Houdini: a magic wand for the future of CSS -...
Devoxx 2014-webComponents
JavaScript Advanced - Useful methods to power up your code
18. images in symfony 4
jQuery Anti-Patterns for Performance & Compression
Borrador del blog
Angular Directives from Scratch
Yearning jQuery
Site optimization
Polymer 1.0
Introduction to JQuery
Ampersandjs
iPhone Web Applications: HTML5, CSS3 & dev tips for iPhone development
Ad

Viewers also liked (15)

PPT
Gabriela Benatti De Oliveira
PPTX
Carciuc stefran cv
PPTX
Curriculum vitae paola priscila davila perez a00736461
PPT
EL CURRICULUM
PPTX
Curriculum vitae
PPT
Curriculum Vitae1
PDF
Portafolio de Max Aguilera
PPTX
CV Creativo ALvaro Prieto Barba
DOCX
Cuadro comparativo de red
DOCX
Curriculum de Yalixha
PDF
Curriculum vitae 2013 personal
PDF
CV original para revista de moda
DOCX
Curriculum vitae
PDF
Designing Teams for Emerging Challenges
PDF
How to Become a Thought Leader in Your Niche
Gabriela Benatti De Oliveira
Carciuc stefran cv
Curriculum vitae paola priscila davila perez a00736461
EL CURRICULUM
Curriculum vitae
Curriculum Vitae1
Portafolio de Max Aguilera
CV Creativo ALvaro Prieto Barba
Cuadro comparativo de red
Curriculum de Yalixha
Curriculum vitae 2013 personal
CV original para revista de moda
Curriculum vitae
Designing Teams for Emerging Challenges
How to Become a Thought Leader in Your Niche
Ad

Similar to Quick ref capybara (20)

PDF
Capybara
PDF
Functional testing with capybara
PPTX
Python Code Camp for Professionals 1/4
PDF
Wynn Netherland: Accelerating Titanium Development with CoffeeScript, Compass...
PDF
前端MVC 豆瓣说
PPTX
Introduce cucumber
KEY
Jarv.us Showcase — SenchaCon 2011
PDF
Vue routing tutorial getting started with vue router
PDF
Mobile Open Day: React Native: Crossplatform fast dive
PDF
GDI Seattle - Intro to JavaScript Class 4
PDF
Blog Hacks 2011
PDF
Embracing Capybara
PDF
Enabling agile devliery through enabling BDD in PHP projects
PDF
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
PPTX
Python Code Camp for Professionals 4/4
KEY
Prateek dayal backbonerails-110528024926-phpapp02
KEY
Single Page Web Apps with Backbone.js and Rails
PDF
Angular 2 Essential Training
KEY
Geek Moot '09 -- Smarty 101
PDF
RubyBarCamp “Полезные gems и plugins”
Capybara
Functional testing with capybara
Python Code Camp for Professionals 1/4
Wynn Netherland: Accelerating Titanium Development with CoffeeScript, Compass...
前端MVC 豆瓣说
Introduce cucumber
Jarv.us Showcase — SenchaCon 2011
Vue routing tutorial getting started with vue router
Mobile Open Day: React Native: Crossplatform fast dive
GDI Seattle - Intro to JavaScript Class 4
Blog Hacks 2011
Embracing Capybara
Enabling agile devliery through enabling BDD in PHP projects
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
Python Code Camp for Professionals 4/4
Prateek dayal backbonerails-110528024926-phpapp02
Single Page Web Apps with Backbone.js and Rails
Angular 2 Essential Training
Geek Moot '09 -- Smarty 101
RubyBarCamp “Полезные gems и plugins”

Recently uploaded (20)

PDF
Introduction to the IoT system, how the IoT system works
PPTX
Reading as a good Form of Recreation
PDF
si manuel quezon at mga nagawa sa bansang pilipinas
PDF
Session 1 (Week 1)fghjmgfdsfgthyjkhfdsadfghjkhgfdsa
PPTX
Layers_of_the_Earth_Grade7.pptx class by
PPTX
APNIC Report, presented at APAN 60 by Thy Boskovic
PPTX
E -tech empowerment technologies PowerPoint
PPT
12 Things That Make People Trust a Website Instantly
PDF
📍 LABUAN4D EXCLUSIVE SERVER STAR GAMING ASIA NO.1 TERPOPULER DI INDONESIA ! 🌟
PDF
Uptota Investor Deck - Where Africa Meets Blockchain
PDF
Alethe Consulting Corporate Profile and Solution Aproach
PPT
isotopes_sddsadsaadasdasdasdasdsa1213.ppt
PDF
Smart Home Technology for Health Monitoring (www.kiu.ac.ug)
PDF
simpleintnettestmetiaerl for the simple testint
PDF
Containerization lab dddddddddddddddmanual.pdf
PPTX
The-Importance-of-School-Sanitation.pptx
PPT
FIRE PREVENTION AND CONTROL PLAN- LUS.FM.MQ.OM.UTM.PLN.00014.ppt
PPTX
newyork.pptxirantrafgshenepalchinachinane
PPT
250152213-Excitation-SystemWERRT (1).ppt
PDF
Slides PDF: The World Game (s) Eco Economic Epochs.pdf
Introduction to the IoT system, how the IoT system works
Reading as a good Form of Recreation
si manuel quezon at mga nagawa sa bansang pilipinas
Session 1 (Week 1)fghjmgfdsfgthyjkhfdsadfghjkhgfdsa
Layers_of_the_Earth_Grade7.pptx class by
APNIC Report, presented at APAN 60 by Thy Boskovic
E -tech empowerment technologies PowerPoint
12 Things That Make People Trust a Website Instantly
📍 LABUAN4D EXCLUSIVE SERVER STAR GAMING ASIA NO.1 TERPOPULER DI INDONESIA ! 🌟
Uptota Investor Deck - Where Africa Meets Blockchain
Alethe Consulting Corporate Profile and Solution Aproach
isotopes_sddsadsaadasdasdasdasdsa1213.ppt
Smart Home Technology for Health Monitoring (www.kiu.ac.ug)
simpleintnettestmetiaerl for the simple testint
Containerization lab dddddddddddddddmanual.pdf
The-Importance-of-School-Sanitation.pptx
FIRE PREVENTION AND CONTROL PLAN- LUS.FM.MQ.OM.UTM.PLN.00014.ppt
newyork.pptxirantrafgshenepalchinachinane
250152213-Excitation-SystemWERRT (1).ppt
Slides PDF: The World Game (s) Eco Economic Epochs.pdf

Quick ref capybara

  • 1. Capybara Exemplos de configuração Com cucumber sem Rails require 'capybara/cucumber' Capybara.app = MyRackApp Com cucumber-rails rails generate cucumber:install -- capybara Nos steps do cucumber When /I sign in/ do within("#session") do fill_in 'Login', :with => 'user@example.com' fill_in 'Password', :with => 'password' end click_link 'Sign in' end Tags para uso de JS @javascript Scenario: do something Ajaxy When I click the Ajax link ... Capybara.javascript_driver = :culerity Tags disponívels @javascript Scenario: do something Ajaxy When I click the Ajax link ... @selenium Scenario: do something Ajaxy When I click the Ajax link ... @culerity Scenario: do something Ajaxy When I click the Ajax link ... @rack_test Scenario: do something Ajaxy When I click the Ajax link ... Utilizando com RSpec require 'capybara/rspec' describe "the signup process", :type => :request do before :each do User.make(:email => 'user@example.com', :password => 'caplin') end it "signs me in" do within("#session") do fill_in 'Login', :with => 'user@example.com' fill_in 'Password', :with => 'password' end click_link 'Sign in' end end
  • 2. Habilitando o driver JS describe 'some stuff which requires js', :js => true do it 'will use the default js driver' it 'will switch to one specific driver', :driver => :celerity end DSL do Capybara feature "Signing up" do background do User.make(:email => 'user@example.com', :password => 'caplin') end scenario "Signing in with correct credentials" do within("#session") do fill_in 'Login', :with => 'user@example.com' fill_in 'Password', :with => 'caplin' end click_link 'Sign in' end end Isto é apenas uma forma de utilizar o RSpec. feature é um alias para describe ..., :type => :request background é um alias para before' scenario é um alias para it/specify Junto com Test::Unit class ActionDispatch::IntegrationTest include Capybara::DSL end Capybara com qualquer aplicação Rack Capybara.app = MyRackApp Selecionando o Driver Capybara.default_driver = :selenium Capybara.current_driver = :rack_test # Este é o padrão se não mudarmos para outro na linha acima Capybara.use_default_driver #volta para o driver padrão A DSL
  • 3. Navegando visit('/projects') visit(post_comments_path(post)) current_path.should == post_comments_path(post) Clicando em links e botões click_link('id-of-link') click_link('Link Text') click_button('Save') click_on('Link Text') # clica em um link ou botão click_on('Button Value') Interagindo com formulários 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') Verificando o conteúdo da página page.has_selector?('table tr') page.has_selector?(:xpath, '//table/tr') page.has_no_selector?(:content) page.has_xpath?('//table/tr') page.has_css?('table tr.foo') page.has_content?('foo') page.has_text?('foo') Verificando o conteúdo da página com RSpec page.should have_selector('table tr') page.should have_selector(:xpath, '//table/tr') page.should have_no_selector(:content) page.should have_xpath('//table/tr') page.should have_css('table tr.foo') page.should have_text('foo') page.should have_no_text('foo') page.html.should match /<span>.../i Buscando find_field('First Name').value find_link('Hello').visible? find_button('Send').click find(:xpath, "//table/tr").click find("#overlay").find("h1").click all('a').each { |a| a[:href] } find('#navigation').click_link('Home') find('#navigation').should have_button('Sign out') Definindo escopos within("li#employee") do fill_in 'Name', :with => 'Jimmy' end within(:xpath, "//li[@id='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 Rodando Javascript page.execute_script("$('body').empty()") result = page.evaluate_script('4 + 4');
  • 4. Debug save_and_open_page Mais exemplos Utilizando a DSL em qualquer lugar require 'capybara' require 'capybara/dsl' Capybara.default_driver = :culerity module MyModule include Capybara::DSL def login! within("//form[@id='session']") do fill_in 'Login', :with => 'user@example.com' fill_in 'Password', :with => 'password' end click_link 'Sign in' end end Chamando servidores remotos visit('http://www.google.com') Capybara.current_driver = :selenium Capybara.app_host = 'http://www.google.com' ... visit('/') Capybara sem o servidor Rack interno Capybara.run_server = false Session require 'capybara' session = Capybara::Session.new(:culerity, my_rack_app) session.within("//form[@id='session']") do session.fill_in 'Login', :with => 'user@example.com' session.fill_in 'Password', :with => 'password' end session.click_link 'Sign in' Seletores XPath within(:xpath, '//ul/li') { ... } find(:xpath, '//ul/li').text find(:xpath, '//li[contains(.//a[@href = "#"]/text(), "foo")]').value Seletores padrão Capybara.default_selector = :xpath find('//ul/li').text
  • 5. Seletores personalizados Capybara.add_selector(:id) do xpath { |id| XPath.descendant[XPath.attr(:id) == id.to_s] } end Capybara.add_selector(:row) do xpath { |num| ".//tbody/tr[#{num}]" } end Capybara.add_selector(:flash_type) do css { |type| "#flash.#{type}" } end find(:id, 'post_123') find(:row, 3) find(:flash_type, :notice) Adicionando drivers Capybara.register_driver :selenium do |app| Capybara::Selenium::Driver.new(app, :browser => :chrome) end Capybara.register_driver :selenium_chrome do |app| Capybara::Selenium::Driver.new(app, :browser => :chrome) end Parte do Livro de Rails 3.1 de Rodrigo Urubatan Ferreira Jardim, guia de referência rápida publicado originalmente em http://www.urubatan.com.br