Capybara and cucumber with DSL using ruby

Capybara with Cucumber
Deepak Chandella
email: deepchandila07@gmail.com
LinkedIn: https://www.linkedin.com/in/deepak-
chandella-084bb75a/
Agenda
 Setup for capybara and cucumber
 Overview and directory structure.
 Capybara using cucumber or any other ruby test framework.
 Setting up the driver.
 The DSL (Navigation, clicking link or button, interacting with forms)
 The DSL (querying, finding, scoping)
 The DSL (windows, scripting, modals, debugging)
 Capybara test execution, tagging, reporting.
Setup for capybara and cucumber
 Install Ruby
 Install Ruby Devkit
 Install the required gem
Setup for capybara and cucumber
Ruby Installation
 Download ruby from source url “http://rubyinstaller.org/downloads/”
preferred version Ruby 2.0.0-p648 (x64) and install it.
 After installation verify the ruby installation by opening the command prompt
and type ruby –version and press enter. You will see the installed ruby version.
 NOTE: Before checking the version you need to set the ruby executables path to
Environment path variable. Ignore if it is already set while installation.
Setup for capybara and cucumber
Ruby Devkit Installation
 Download ruby Devkit from source url “http://rubyinstaller.org/downloads/”
NOTE: Devkit version should be compatible with ruby version that you have
installed.
 Downloaded ruby Devkit is in zip format, extract the downloaded zip file.
 In extracted folder you see dk.rb file. it is development kit installation file
 Open the command prompt and locate the ruby devkit directory where we
have dk.rb file.
 Type “ruby dk.rb init” this cmd will initialize the devkit process.
 Now type “ruby dk.rb install” this command will install the devkit
 Devkit installation is completed.
Setup for capybara and cucumber
Install the required gem
 gem install bundle
 gem install cucumber
 gem install selenium-webdriver
 gem install rspec
 gem install capybara
NOTE: if you found some version dependencies you can install them first with
there supported versions. Also “gem list” command can be used to list all the
installed gems with there versions.
NOTE: if you face SSL issue while gem download you can change the source:
gem sources -r https://rubygems.org/
gem sources -a http://rubygems.org/
Capybara Overview
Capybara
 Capybara is a library written in the Ruby programming language which
makes it easy to simulate how a user interacts with your
application. Capybara can talk with many different drivers which execute
your tests through the same clean and simple interface. You can seamlessly
choose between Selenium, Webkit or pure Ruby drivers.
Capybara Benefits
Capybara Benefits summary
 Open source
 Built-in DSL
 Support multiple drivers
 No setup necessary for Rails and Rack application, it can work with
cucumber, rspec or ruby unit test framework.
Cucumber Overview
Cucumber
 Cucumber is a testing framework which
supports Behaviour Driven Development (BDD). It lets us define
application behaviour in plain meaningful English text using a simple
grammar defined by a language called Gherkin. Cucumber itself is written
inRuby, but it can be used to “test” code written in Ruby or other
languages
Cucumber Benefits
Cucumber benefits summary
 Open source.
 Support multiple languages.
 Style of writing tests allow for easier reuse of code in the tests
 Quick and easy set up and execution
 It is helpful to understand business scenarios written in cucumber.
Cucumber Directory Structure
Directory Structure for Cucumber
step_difinitions
support
features
Feature files
Login.feature
Search.feature
Update.feature
Support files
Env.rb
Step_definitions
files
Test_steps.rb
Capybara with other ruby test framework
Capybara can be used with other ruby testing
frameworks
 Capybara with cucumber
 Capybara with rspec
 Capybara with ruby unit test framework
Capybara with Cucumber
Cucumber test scenarios
 Follow the directory structure mentioned in previous slides and Create a
feature file in features folder and write some test scenarios. Example
below:
Capybara with Cucumber
Implementation of cucumber scenarios using
Capybara.
 Create a ruby file in step_definitions folder and write ruby code to
implement cucumber test scenarios. Example below:
Capybara with Cucumber
Set the driver for test execution.
 Create a env.rb file in support folder and write code to set driver for test
execution. Example below:
NOTE: By only adding capybara.default_driver=:selenium line will also work and
by default tests will be executed on firefox browser.
Capybara with Cucumber
Cucumber test execution.
 Open the command prompt and locate features directory and run the
below command:
 Cucumber featurestest.feature
e.g cucumber features<feature file name>
After the execution of tests summary output can be seen as below:
Time may differ on other machine.
Capybara with Rspec
Rspec
 Rspec is a testing tool for Ruby, created for behavior-driven development
(BDD). It is the most frequently used testing library for Ruby in
production applications. Even though it has a very rich and powerful DSL
(domain-specific language), at its core it is a simple tool which you can
start using rather quickly.
Capybara with Rspec
Rspec test scenario with capybara
Capybara with Rspec
Enough to understand the previous code
 Default driver selenium is used.
 Describe, context and it are keywords of rspec to give more clarity to the
scenarios. They can take a class name or string argument.
 Visit, fill_in and click_button are methods of capybara.
 Expect (page) is rspec expectation.
NOTE: Execute the script with cmd “rspec <file_name.rb>”
Capybara with ruby unit test framework
 Ruby’s Test::Unit
The general idea behind unit testing is that you write a test method that
makes certain assertions about your code, working against a test fixture. A
bunch of these test methods are bundled up into a test suite and can be run
any time the developer wants. To write a test, follow these steps:
 require ‘test/unit’ in your test script.
 Create a class that subclasses Test::Unit::TestCase.
 Add a method that begins with “test” to your class.
 Make assertions in your test method.
 Optionally define setup and/or teardown to set up and/or tear down
your common test fixture.
 You can now run your test as you would any other Ruby script
Capybara with ruby unit test framework
 Ruby unit test scenario with capybara
Setting up the driver
 Capybara drivers
 RackTest
 Selenium
 Capybara-webkit
Setting up the driver
 Racktest driver
 RackTest is Capybara's default driver. It is written in pure Ruby and does
not have any support for executing JavaScript. Since the RackTest driver
interacts directly with Rack interfaces, it does not require a server to be
started. However, this means that if your application is not a Rack
application (Rails, Sinatra and most other Ruby frameworks are Rack
applications) then you cannot use this driver. Furthermore, you cannot
use the RackTest driver to test a remote application, or to access remote
URLs (e.g., redirects to external sites, external APIs, or OAuth services)
that your application might interact with.
Setting up the driver
 Racktest driver
 To use racktest driver add gem
 Gem install cucumber-rails
If dependency occur add activesupport or
other dependent gems
Setting up the driver
 Selenium driver
 At the moment, Capybara supports Selenium 2.0+
(Webdriver), not Selenium RC. In order to use Selenium, you'll need to
install the selenium-webdriver gem, and add it to your Gemfile if you're
using bundler. Provided Firefox is installed, everything is set up for you,
and you should be able to start using Selenium right away.
Setting up the driver
 Selenium webdriver setup
 Add the below line of code to your env.rb file
 You can even set the browser profile, by registering the browser as below.
NOTE: by default firefox browser is used.
Setting up the driver
 Capybara-webkit driver
 The capybara-webkit driver is for true headless testing. It uses QtWebKit
to start a rendering engine process. It can execute JavaScript as well. It is
significantly faster than drivers like Selenium since it does not load an
entire browser.
 You can install it with:
gem install capybara-webkit
 you can use it by:
Capybara.javascript_driver = :webkit
About DSL
 DSL (Domain Specific language)
 A domain-specific language (DSL) is a computer language specialized to a
particular application domain. This is in contrast to a general-purpose
language (GPL), which is broadly applicable across domains. There is a
wide variety of DSLs, ranging from widely used languages for common
domains, such as HTML for web pages.
 Capybara offers a user-friendly DSL (Domain Specific Language) which is
used to describe actions that are executed by the underlying web driver
DSL (Navigation)
 Navigation
 ‘visit’ method can be used to navigate to web pages
 The visit method only takes a single parameter, the request method
is always GET.
 Syntax:
visit('/projects')
visit(post_comments_path(post))
 You can get the current path of the browsing session, and test it using
the have_current_path matcher, example below:
expect(page).to have_current_path(post_comments_path(post))
DSL (Clicking Elements)
 Clicking elements
You can interact with the webapp by following links and buttons. Capybara
automatically follows any redirects, and submits forms associated with buttons.
 click_link('id-of-link')
 click_link('Link Text')
 click_button('Save')
 click_on('Link Text') # clicks on either links or buttons
 click_on('Button Value')
DSL (Interacting with forms)
 Interacting with forms
Following methods can be used to interact with web forms.
 fill_in('First Name', with: 'John')
 fill_in('Password', with: ‘John123')
 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')
NOTE: There are number of methods in capybara to interact with web forms,
you can query the text box using find method and fill the values with set
method. Attach_file method checks the existence of file before attaching it
to web page.
DSL (Querying)
 Querying
Capybara has a rich set of options for querying the page for the existence of
certain elements, and working with and manipulating those elements.
 page.has_selector?('table tr')
 page.has_selector?(:xpath, './/table/tr')
 page.has_xpath?('.//table/tr')
 page.has_css?('table tr.foo')
 page.has_content?('foo')
You can use these with RSpec's magic matchers:
 expect(page).to have_selector('table tr')
 expect(page).to have_selector(:xpath, './/table/tr')
 expect(page).to have_xpath('.//table/tr')
 expect(page).to have_css('table tr.foo')
 expect(page).to have_content('foo')
DSL (Finding Elements)
 Finding Elements
You can also find specific elements, in order to manipulate them:
 find_field('First Name').value
 find_field(id: 'my_field').value
 find_link('Hello', :visible => :all).visible?
 find_link(class: ['some_class', 'some_other_class'], :visible => :all).visible?
 find_button('Send').click
 find_button(value: '1234').click
 find(:xpath, ".//table/tr").click
 find("#overlay").find("h1").click all('a').each { |a| a[:href] }
DSL (Scoping)
 Scoping
Capybara makes it possible to restrict certain actions, such as interacting with
forms or clicking links and buttons, to within a specific area of the page. For this
purpose you can use the generic within method. Optionally you can specify which
kind of selector to use.
 within("li#employee") do
fill_in 'Name', with: 'Jimmy'
end
 within(:xpath, ".//li[@id='employee']") do
fill_in 'Name', with: 'Jimmy‘
end
DSL (Working with windows)
 Working with windows
Capybara provides some methods to ease finding and switching windows:
facebook_window = window_opened_by do
click_button 'Like‘
end
within_window facebook_window do
find('#login_email').set('a@example.com')
find('#login_password').set('qwerty')
click_button 'Submit'
end
DSL (Scripting)
 Scripting
Javascript can be used in drivers which are supported.
 Javascript example:
page.execute_script("$('body').empty()")
page.evaluate_script("window.location.reload()")
 Jquery example:
page.execute_script %Q{
document.getElementById('file_upload1').style.display = "block";
}
DSL (Handling Modals)
 Scripting
In drivers which support it, you can accept, dismiss and respond to alerts,
confirms and prompts.
 accept or dismiss alert messages
accept_alert do
click_link('Show Alert')
end
 accept or dismiss a confirmation
dismiss_confirm do
click_link('Show Confirm')
end
DSL (Handling Modals Continue)
 Scripting
 accept or dismiss prompts
accept_prompt(with: 'Linus Torvalds') do
click_link('Show Prompt About Linux')
end
 Verifying the return messages from modals
message = accept_prompt(with: 'Linus Torvalds') do
click_link('Show Prompt About Linux')
end
expect(message).to eq('Who is the chief architect of Linux?')
DSL (Debugging)
 Debugging
Debugging for tests can be done using below methods
 Take a snapshot of the page
page.save_screenshot('screenshot.png')
 Retrieve the current state of the DOM as a string
print page.html
NOTE: You should avoid testing against the contents of page.html and
use the more expressive finder methods instead.
DSL (Matching)
 Matching
It is possible to customize how Capybara finds elements. There are two options
available:
 Exactness (Capybara.exact)
 Strategy (Capybara.match)
DSL (Matching)
 Matching (Exactness)
Capybara.exact and the exact option work together with the is expression inside
the XPath gem. When exact is true, all is expressions match exactly, when it is
false, they allow substring matches. Many of the selectors built into Capybara use
the is expression. This way you can specify whether you want to allow substring
matches or not. Capybara.exact is false by default.
 For example:
click_link("Password") # also matches "Password confirmation"
Capybara.exact = true
click_link("Password") # does not match "Password confirmation"
click_link("Password", exact: false) # can be overridden
DSL (Matching)
 Matching (Strategy)
Using Capybara.match and the equivalent match option, you can control how
Capybara behaves when multiple elements all match a query. There are currently
four different strategies built into Capybara:
 first: Just picks the first element that matches.
 one: Raises an error if more than one element matches.
 smart: If exact is true, raises an error if more than one element matches,
just like one. If exact is false, it will first try to find an exact match. An
error is raised if more than one element is found. If no element is found,
a new search is performed which allows partial matches. If that search
returns multiple matches, an error is raised.
 prefer_exact: If multiple matches are found, some of which are exact,
and some of which are not, then the first exactly matching element is
returned.
NOTE: The default value for Capybara.match is :smart
Capybara hooks
 Hooks with cucumber tags
Capybara uses hooks to run setup and teardown for the test cases. hooks adds
the before test and after test scenarios.
 Before hook: It is used as setup for test case.
 After hook: It is used as teardown for test case.
NOTE: @fileUpload and @fileDownload are cucumber tags.
Cucumber Command line options
 Cucumber command line
You can check the available command line options in cucumber with command:
“cucumber –help”. Below are some of the useful options.
 --require : Require files before executing the features. If this option is not
specified, all *.rb files that are siblings or below the features will be
loaded auto-matically. Automatic loading is disabled when this option is
specified, and all loading becomes explicit. Files under directories named
"support" are always loaded first.
 --format : How to format features. Available formats:
 Debug
 Html
 Json
 Pretty
NOTE: The default value for --format is pretty.
Cucumber Command line options
 Cucumber command line (Continue)
You can check the available command line options in cucumber with command:
“cucumber –help”. Below are some of the useful options.
 --out : Write output to a file/directory instead of STDOUT. This option
applies to the previously specified –format. e.g –out report.html
 --tags : Only execute the features or scenarios with tags matching. e.g –
tags @login
 --dry-run : Invokes formatters without executing the steps. Check for test
steps if they are implemented or not.
NOTE: You can check the available formats functionality by with help option.
Cucumber Test Execution and Reporting
 Cucumber Execution
 Command to execute all cucumber tests : Open the command prompt
and locate to features directory and type “cucumber” press enter. It will
execute all the cucumber test scenarios alphabetically.
 Command to execute tests with specific tag : run command
“cucumber –tags @login” this will only execute scenarios with login tag.
 Command to execute tests and generate html reports : Run command :
“cucumber –tags @login –format html –out report.html” this will
execute scenarios with login tag and generate a report.html file in same
directory from where the tests have been executed.
Thank You
1 von 47

Recomendados

Scalable Django Architecture von
Scalable Django ArchitectureScalable Django Architecture
Scalable Django ArchitectureRami Sayar
12.5K views40 Folien
Cooking Perl with Chef: Real World Tutorial with Jitterbug von
Cooking Perl with Chef: Real World Tutorial with JitterbugCooking Perl with Chef: Real World Tutorial with Jitterbug
Cooking Perl with Chef: Real World Tutorial with JitterbugDavid Golden
5.2K views15 Folien
How to develop Jenkins plugin using to ruby and Jenkins.rb von
How to develop Jenkins plugin using to ruby and Jenkins.rbHow to develop Jenkins plugin using to ruby and Jenkins.rb
How to develop Jenkins plugin using to ruby and Jenkins.rbHiroshi SHIBATA
1.1K views76 Folien
PECL Picks - Extensions to make your life better von
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterZendCon
4.1K views74 Folien
Ruby On Rails von
Ruby On RailsRuby On Rails
Ruby On RailsEric Berry
3.6K views48 Folien
Faster Java EE Builds with Gradle von
Faster Java EE Builds with GradleFaster Java EE Builds with Gradle
Faster Java EE Builds with GradleRyan Cuprak
492 views71 Folien

Más contenido relacionado

Was ist angesagt?

Scripting Yor Java Application with BSF3 von
Scripting Yor Java Application with BSF3Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3day
1.2K views36 Folien
Maven Introduction von
Maven IntroductionMaven Introduction
Maven IntroductionSandeep Chawla
21.2K views31 Folien
How DSL works on Ruby von
How DSL works on RubyHow DSL works on Ruby
How DSL works on RubyHiroshi SHIBATA
5.1K views64 Folien
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course von
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Coursepeter_marklund
81.9K views341 Folien
What’s new in laravel 9 von
What’s new in laravel 9What’s new in laravel 9
What’s new in laravel 9Katy Slemon
89 views18 Folien
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda? von
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?Julian Robichaux
551 views66 Folien

Was ist angesagt?(20)

Scripting Yor Java Application with BSF3 von day
Scripting Yor Java Application with BSF3Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3
day1.2K views
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course von peter_marklund
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
peter_marklund81.9K views
What’s new in laravel 9 von Katy Slemon
What’s new in laravel 9What’s new in laravel 9
What’s new in laravel 9
Katy Slemon89 views
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda? von Julian Robichaux
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Julian Robichaux551 views
Maven 3 Overview von Mike Ensor
Maven 3  OverviewMaven 3  Overview
Maven 3 Overview
Mike Ensor2.7K views
How to dockerize rails application compose and rails tutorial von Katy Slemon
How to dockerize rails application compose and rails tutorialHow to dockerize rails application compose and rails tutorial
How to dockerize rails application compose and rails tutorial
Katy Slemon53 views
Preparing your code for Java 9 von Deepu Xavier
Preparing your code for Java 9Preparing your code for Java 9
Preparing your code for Java 9
Deepu Xavier591 views
Mete Atamel von CodeFest
Mete AtamelMete Atamel
Mete Atamel
CodeFest338 views
Deploying Symfony | symfony.cat von Pablo Godel
Deploying Symfony | symfony.catDeploying Symfony | symfony.cat
Deploying Symfony | symfony.cat
Pablo Godel2.8K views
Maven plugins, properties en profiles: Advanced concepts in Maven von Geert Pante
Maven plugins, properties en profiles: Advanced concepts in MavenMaven plugins, properties en profiles: Advanced concepts in Maven
Maven plugins, properties en profiles: Advanced concepts in Maven
Geert Pante2.6K views
Dynamic Languages Web Frameworks Indicthreads 2009 von Arun Gupta
Dynamic Languages Web Frameworks Indicthreads 2009Dynamic Languages Web Frameworks Indicthreads 2009
Dynamic Languages Web Frameworks Indicthreads 2009
Arun Gupta1.3K views
Short Lived Tasks in Cloud Foundry #cfdtokyo von Toshiaki Maki
Short Lived Tasks in Cloud Foundry #cfdtokyoShort Lived Tasks in Cloud Foundry #cfdtokyo
Short Lived Tasks in Cloud Foundry #cfdtokyo
Toshiaki Maki1.5K views
Maven von feng lee
MavenMaven
Maven
feng lee1.8K views
Workflow automation for Front-end web applications von Mayank Patel
Workflow automation for Front-end web applicationsWorkflow automation for Front-end web applications
Workflow automation for Front-end web applications
Mayank Patel1.1K views
Leave end-to-end testing to Capybara von Hiroshi SHIBATA
Leave end-to-end testing to CapybaraLeave end-to-end testing to Capybara
Leave end-to-end testing to Capybara
Hiroshi SHIBATA2.3K views

Similar a Capybara and cucumber with DSL using ruby

Behavioural Testing Ruby/Rails Apps @ Scale - Rspec & Cucumber von
       Behavioural Testing Ruby/Rails Apps @ Scale - Rspec & Cucumber       Behavioural Testing Ruby/Rails Apps @ Scale - Rspec & Cucumber
Behavioural Testing Ruby/Rails Apps @ Scale - Rspec & CucumberUdaya Kiran
183 views18 Folien
Integration and Acceptance Testing von
Integration and Acceptance TestingIntegration and Acceptance Testing
Integration and Acceptance TestingAlan Hecht
4.4K views30 Folien
TorqueBox von
TorqueBoxTorqueBox
TorqueBoxbobmcwhirter
1.2K views114 Folien
Jsp and jstl von
Jsp and jstlJsp and jstl
Jsp and jstlvishal choudhary
78 views27 Folien
Basic RSpec 2 von
Basic RSpec 2Basic RSpec 2
Basic RSpec 2Triet Le Minh
2K views49 Folien
Instruments ruby on rails von
Instruments ruby on railsInstruments ruby on rails
Instruments ruby on railspmashchak
1.3K views11 Folien

Similar a Capybara and cucumber with DSL using ruby(20)

Behavioural Testing Ruby/Rails Apps @ Scale - Rspec & Cucumber von Udaya Kiran
       Behavioural Testing Ruby/Rails Apps @ Scale - Rspec & Cucumber       Behavioural Testing Ruby/Rails Apps @ Scale - Rspec & Cucumber
Behavioural Testing Ruby/Rails Apps @ Scale - Rspec & Cucumber
Udaya Kiran183 views
Integration and Acceptance Testing von Alan Hecht
Integration and Acceptance TestingIntegration and Acceptance Testing
Integration and Acceptance Testing
Alan Hecht4.4K views
Instruments ruby on rails von pmashchak
Instruments ruby on railsInstruments ruby on rails
Instruments ruby on rails
pmashchak1.3K views
Installing spark scala console in windows 10 von Ankit Kaneri
Installing spark scala console in windows 10Installing spark scala console in windows 10
Installing spark scala console in windows 10
Ankit Kaneri58 views
End-to-end web-testing in ruby ecosystem von Alex Mikitenko
End-to-end web-testing in ruby ecosystemEnd-to-end web-testing in ruby ecosystem
End-to-end web-testing in ruby ecosystem
Alex Mikitenko608 views
Play Support in Cloud Foundry von rajdeep
Play Support in Cloud FoundryPlay Support in Cloud Foundry
Play Support in Cloud Foundry
rajdeep1.5K views
Functional Scala 2022 - scalajs Alexis.pdf von ssusercd195b
Functional Scala 2022 - scalajs Alexis.pdfFunctional Scala 2022 - scalajs Alexis.pdf
Functional Scala 2022 - scalajs Alexis.pdf
ssusercd195b23 views
Aspose pdf von Jim Jones
Aspose pdfAspose pdf
Aspose pdf
Jim Jones1.2K views
Viridians on Rails von Viridians
Viridians on RailsViridians on Rails
Viridians on Rails
Viridians444 views
Ruby on rails integration testing with minitest and capybara von Andolasoft Inc
Ruby on rails integration testing with minitest and capybaraRuby on rails integration testing with minitest and capybara
Ruby on rails integration testing with minitest and capybara
Andolasoft Inc186 views
COP_RoR_QuArrk_Session_Oct_2022.pptx von Nitesh95975
COP_RoR_QuArrk_Session_Oct_2022.pptxCOP_RoR_QuArrk_Session_Oct_2022.pptx
COP_RoR_QuArrk_Session_Oct_2022.pptx
Nitesh959754 views

Último

The Path to DevOps von
The Path to DevOpsThe Path to DevOps
The Path to DevOpsJohn Valentino
5 views6 Folien
Ports-and-Adapters Architecture for Embedded HMI von
Ports-and-Adapters Architecture for Embedded HMIPorts-and-Adapters Architecture for Embedded HMI
Ports-and-Adapters Architecture for Embedded HMIBurkhard Stubert
29 views19 Folien
360 graden fabriek von
360 graden fabriek360 graden fabriek
360 graden fabriekinfo33492
162 views25 Folien
Sprint 226 von
Sprint 226Sprint 226
Sprint 226ManageIQ
11 views18 Folien
Benefits in Software Development von
Benefits in Software DevelopmentBenefits in Software Development
Benefits in Software DevelopmentJohn Valentino
5 views15 Folien
Electronic AWB - Electronic Air Waybill von
Electronic AWB - Electronic Air Waybill Electronic AWB - Electronic Air Waybill
Electronic AWB - Electronic Air Waybill Freightoscope
5 views1 Folie

Último(20)

Ports-and-Adapters Architecture for Embedded HMI von Burkhard Stubert
Ports-and-Adapters Architecture for Embedded HMIPorts-and-Adapters Architecture for Embedded HMI
Ports-and-Adapters Architecture for Embedded HMI
Burkhard Stubert29 views
360 graden fabriek von info33492
360 graden fabriek360 graden fabriek
360 graden fabriek
info33492162 views
Sprint 226 von ManageIQ
Sprint 226Sprint 226
Sprint 226
ManageIQ11 views
Electronic AWB - Electronic Air Waybill von Freightoscope
Electronic AWB - Electronic Air Waybill Electronic AWB - Electronic Air Waybill
Electronic AWB - Electronic Air Waybill
Freightoscope 5 views
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium... von Lisi Hocke
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Lisi Hocke35 views
DRYiCE™ iAutomate: AI-enhanced Intelligent Runbook Automation von HCLSoftware
DRYiCE™ iAutomate: AI-enhanced Intelligent Runbook AutomationDRYiCE™ iAutomate: AI-enhanced Intelligent Runbook Automation
DRYiCE™ iAutomate: AI-enhanced Intelligent Runbook Automation
HCLSoftware6 views
ADDO_2022_CICID_Tom_Halpin.pdf von TomHalpin9
ADDO_2022_CICID_Tom_Halpin.pdfADDO_2022_CICID_Tom_Halpin.pdf
ADDO_2022_CICID_Tom_Halpin.pdf
TomHalpin95 views
JioEngage_Presentation.pptx von admin125455
JioEngage_Presentation.pptxJioEngage_Presentation.pptx
JioEngage_Presentation.pptx
admin1254558 views
How Workforce Management Software Empowers SMEs | TraQSuite von TraQSuite
How Workforce Management Software Empowers SMEs | TraQSuiteHow Workforce Management Software Empowers SMEs | TraQSuite
How Workforce Management Software Empowers SMEs | TraQSuite
TraQSuite6 views
FIMA 2023 Neo4j & FS - Entity Resolution.pptx von Neo4j
FIMA 2023 Neo4j & FS - Entity Resolution.pptxFIMA 2023 Neo4j & FS - Entity Resolution.pptx
FIMA 2023 Neo4j & FS - Entity Resolution.pptx
Neo4j17 views

Capybara and cucumber with DSL using ruby

  • 1. Capybara with Cucumber Deepak Chandella email: deepchandila07@gmail.com LinkedIn: https://www.linkedin.com/in/deepak- chandella-084bb75a/
  • 2. Agenda  Setup for capybara and cucumber  Overview and directory structure.  Capybara using cucumber or any other ruby test framework.  Setting up the driver.  The DSL (Navigation, clicking link or button, interacting with forms)  The DSL (querying, finding, scoping)  The DSL (windows, scripting, modals, debugging)  Capybara test execution, tagging, reporting.
  • 3. Setup for capybara and cucumber  Install Ruby  Install Ruby Devkit  Install the required gem
  • 4. Setup for capybara and cucumber Ruby Installation  Download ruby from source url “http://rubyinstaller.org/downloads/” preferred version Ruby 2.0.0-p648 (x64) and install it.  After installation verify the ruby installation by opening the command prompt and type ruby –version and press enter. You will see the installed ruby version.  NOTE: Before checking the version you need to set the ruby executables path to Environment path variable. Ignore if it is already set while installation.
  • 5. Setup for capybara and cucumber Ruby Devkit Installation  Download ruby Devkit from source url “http://rubyinstaller.org/downloads/” NOTE: Devkit version should be compatible with ruby version that you have installed.  Downloaded ruby Devkit is in zip format, extract the downloaded zip file.  In extracted folder you see dk.rb file. it is development kit installation file  Open the command prompt and locate the ruby devkit directory where we have dk.rb file.  Type “ruby dk.rb init” this cmd will initialize the devkit process.  Now type “ruby dk.rb install” this command will install the devkit  Devkit installation is completed.
  • 6. Setup for capybara and cucumber Install the required gem  gem install bundle  gem install cucumber  gem install selenium-webdriver  gem install rspec  gem install capybara NOTE: if you found some version dependencies you can install them first with there supported versions. Also “gem list” command can be used to list all the installed gems with there versions. NOTE: if you face SSL issue while gem download you can change the source: gem sources -r https://rubygems.org/ gem sources -a http://rubygems.org/
  • 7. Capybara Overview Capybara  Capybara is a library written in the Ruby programming language which makes it easy to simulate how a user interacts with your application. Capybara can talk with many different drivers which execute your tests through the same clean and simple interface. You can seamlessly choose between Selenium, Webkit or pure Ruby drivers.
  • 8. Capybara Benefits Capybara Benefits summary  Open source  Built-in DSL  Support multiple drivers  No setup necessary for Rails and Rack application, it can work with cucumber, rspec or ruby unit test framework.
  • 9. Cucumber Overview Cucumber  Cucumber is a testing framework which supports Behaviour Driven Development (BDD). It lets us define application behaviour in plain meaningful English text using a simple grammar defined by a language called Gherkin. Cucumber itself is written inRuby, but it can be used to “test” code written in Ruby or other languages
  • 10. Cucumber Benefits Cucumber benefits summary  Open source.  Support multiple languages.  Style of writing tests allow for easier reuse of code in the tests  Quick and easy set up and execution  It is helpful to understand business scenarios written in cucumber.
  • 11. Cucumber Directory Structure Directory Structure for Cucumber step_difinitions support features Feature files Login.feature Search.feature Update.feature Support files Env.rb Step_definitions files Test_steps.rb
  • 12. Capybara with other ruby test framework Capybara can be used with other ruby testing frameworks  Capybara with cucumber  Capybara with rspec  Capybara with ruby unit test framework
  • 13. Capybara with Cucumber Cucumber test scenarios  Follow the directory structure mentioned in previous slides and Create a feature file in features folder and write some test scenarios. Example below:
  • 14. Capybara with Cucumber Implementation of cucumber scenarios using Capybara.  Create a ruby file in step_definitions folder and write ruby code to implement cucumber test scenarios. Example below:
  • 15. Capybara with Cucumber Set the driver for test execution.  Create a env.rb file in support folder and write code to set driver for test execution. Example below: NOTE: By only adding capybara.default_driver=:selenium line will also work and by default tests will be executed on firefox browser.
  • 16. Capybara with Cucumber Cucumber test execution.  Open the command prompt and locate features directory and run the below command:  Cucumber featurestest.feature e.g cucumber features<feature file name> After the execution of tests summary output can be seen as below: Time may differ on other machine.
  • 17. Capybara with Rspec Rspec  Rspec is a testing tool for Ruby, created for behavior-driven development (BDD). It is the most frequently used testing library for Ruby in production applications. Even though it has a very rich and powerful DSL (domain-specific language), at its core it is a simple tool which you can start using rather quickly.
  • 18. Capybara with Rspec Rspec test scenario with capybara
  • 19. Capybara with Rspec Enough to understand the previous code  Default driver selenium is used.  Describe, context and it are keywords of rspec to give more clarity to the scenarios. They can take a class name or string argument.  Visit, fill_in and click_button are methods of capybara.  Expect (page) is rspec expectation. NOTE: Execute the script with cmd “rspec <file_name.rb>”
  • 20. Capybara with ruby unit test framework  Ruby’s Test::Unit The general idea behind unit testing is that you write a test method that makes certain assertions about your code, working against a test fixture. A bunch of these test methods are bundled up into a test suite and can be run any time the developer wants. To write a test, follow these steps:  require ‘test/unit’ in your test script.  Create a class that subclasses Test::Unit::TestCase.  Add a method that begins with “test” to your class.  Make assertions in your test method.  Optionally define setup and/or teardown to set up and/or tear down your common test fixture.  You can now run your test as you would any other Ruby script
  • 21. Capybara with ruby unit test framework  Ruby unit test scenario with capybara
  • 22. Setting up the driver  Capybara drivers  RackTest  Selenium  Capybara-webkit
  • 23. Setting up the driver  Racktest driver  RackTest is Capybara's default driver. It is written in pure Ruby and does not have any support for executing JavaScript. Since the RackTest driver interacts directly with Rack interfaces, it does not require a server to be started. However, this means that if your application is not a Rack application (Rails, Sinatra and most other Ruby frameworks are Rack applications) then you cannot use this driver. Furthermore, you cannot use the RackTest driver to test a remote application, or to access remote URLs (e.g., redirects to external sites, external APIs, or OAuth services) that your application might interact with.
  • 24. Setting up the driver  Racktest driver  To use racktest driver add gem  Gem install cucumber-rails If dependency occur add activesupport or other dependent gems
  • 25. Setting up the driver  Selenium driver  At the moment, Capybara supports Selenium 2.0+ (Webdriver), not Selenium RC. In order to use Selenium, you'll need to install the selenium-webdriver gem, and add it to your Gemfile if you're using bundler. Provided Firefox is installed, everything is set up for you, and you should be able to start using Selenium right away.
  • 26. Setting up the driver  Selenium webdriver setup  Add the below line of code to your env.rb file  You can even set the browser profile, by registering the browser as below. NOTE: by default firefox browser is used.
  • 27. Setting up the driver  Capybara-webkit driver  The capybara-webkit driver is for true headless testing. It uses QtWebKit to start a rendering engine process. It can execute JavaScript as well. It is significantly faster than drivers like Selenium since it does not load an entire browser.  You can install it with: gem install capybara-webkit  you can use it by: Capybara.javascript_driver = :webkit
  • 28. About DSL  DSL (Domain Specific language)  A domain-specific language (DSL) is a computer language specialized to a particular application domain. This is in contrast to a general-purpose language (GPL), which is broadly applicable across domains. There is a wide variety of DSLs, ranging from widely used languages for common domains, such as HTML for web pages.  Capybara offers a user-friendly DSL (Domain Specific Language) which is used to describe actions that are executed by the underlying web driver
  • 29. DSL (Navigation)  Navigation  ‘visit’ method can be used to navigate to web pages  The visit method only takes a single parameter, the request method is always GET.  Syntax: visit('/projects') visit(post_comments_path(post))  You can get the current path of the browsing session, and test it using the have_current_path matcher, example below: expect(page).to have_current_path(post_comments_path(post))
  • 30. DSL (Clicking Elements)  Clicking elements You can interact with the webapp by following links and buttons. Capybara automatically follows any redirects, and submits forms associated with buttons.  click_link('id-of-link')  click_link('Link Text')  click_button('Save')  click_on('Link Text') # clicks on either links or buttons  click_on('Button Value')
  • 31. DSL (Interacting with forms)  Interacting with forms Following methods can be used to interact with web forms.  fill_in('First Name', with: 'John')  fill_in('Password', with: ‘John123')  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') NOTE: There are number of methods in capybara to interact with web forms, you can query the text box using find method and fill the values with set method. Attach_file method checks the existence of file before attaching it to web page.
  • 32. DSL (Querying)  Querying Capybara has a rich set of options for querying the page for the existence of certain elements, and working with and manipulating those elements.  page.has_selector?('table tr')  page.has_selector?(:xpath, './/table/tr')  page.has_xpath?('.//table/tr')  page.has_css?('table tr.foo')  page.has_content?('foo') You can use these with RSpec's magic matchers:  expect(page).to have_selector('table tr')  expect(page).to have_selector(:xpath, './/table/tr')  expect(page).to have_xpath('.//table/tr')  expect(page).to have_css('table tr.foo')  expect(page).to have_content('foo')
  • 33. DSL (Finding Elements)  Finding Elements You can also find specific elements, in order to manipulate them:  find_field('First Name').value  find_field(id: 'my_field').value  find_link('Hello', :visible => :all).visible?  find_link(class: ['some_class', 'some_other_class'], :visible => :all).visible?  find_button('Send').click  find_button(value: '1234').click  find(:xpath, ".//table/tr").click  find("#overlay").find("h1").click all('a').each { |a| a[:href] }
  • 34. DSL (Scoping)  Scoping Capybara makes it possible to restrict certain actions, such as interacting with forms or clicking links and buttons, to within a specific area of the page. For this purpose you can use the generic within method. Optionally you can specify which kind of selector to use.  within("li#employee") do fill_in 'Name', with: 'Jimmy' end  within(:xpath, ".//li[@id='employee']") do fill_in 'Name', with: 'Jimmy‘ end
  • 35. DSL (Working with windows)  Working with windows Capybara provides some methods to ease finding and switching windows: facebook_window = window_opened_by do click_button 'Like‘ end within_window facebook_window do find('#login_email').set('a@example.com') find('#login_password').set('qwerty') click_button 'Submit' end
  • 36. DSL (Scripting)  Scripting Javascript can be used in drivers which are supported.  Javascript example: page.execute_script("$('body').empty()") page.evaluate_script("window.location.reload()")  Jquery example: page.execute_script %Q{ document.getElementById('file_upload1').style.display = "block"; }
  • 37. DSL (Handling Modals)  Scripting In drivers which support it, you can accept, dismiss and respond to alerts, confirms and prompts.  accept or dismiss alert messages accept_alert do click_link('Show Alert') end  accept or dismiss a confirmation dismiss_confirm do click_link('Show Confirm') end
  • 38. DSL (Handling Modals Continue)  Scripting  accept or dismiss prompts accept_prompt(with: 'Linus Torvalds') do click_link('Show Prompt About Linux') end  Verifying the return messages from modals message = accept_prompt(with: 'Linus Torvalds') do click_link('Show Prompt About Linux') end expect(message).to eq('Who is the chief architect of Linux?')
  • 39. DSL (Debugging)  Debugging Debugging for tests can be done using below methods  Take a snapshot of the page page.save_screenshot('screenshot.png')  Retrieve the current state of the DOM as a string print page.html NOTE: You should avoid testing against the contents of page.html and use the more expressive finder methods instead.
  • 40. DSL (Matching)  Matching It is possible to customize how Capybara finds elements. There are two options available:  Exactness (Capybara.exact)  Strategy (Capybara.match)
  • 41. DSL (Matching)  Matching (Exactness) Capybara.exact and the exact option work together with the is expression inside the XPath gem. When exact is true, all is expressions match exactly, when it is false, they allow substring matches. Many of the selectors built into Capybara use the is expression. This way you can specify whether you want to allow substring matches or not. Capybara.exact is false by default.  For example: click_link("Password") # also matches "Password confirmation" Capybara.exact = true click_link("Password") # does not match "Password confirmation" click_link("Password", exact: false) # can be overridden
  • 42. DSL (Matching)  Matching (Strategy) Using Capybara.match and the equivalent match option, you can control how Capybara behaves when multiple elements all match a query. There are currently four different strategies built into Capybara:  first: Just picks the first element that matches.  one: Raises an error if more than one element matches.  smart: If exact is true, raises an error if more than one element matches, just like one. If exact is false, it will first try to find an exact match. An error is raised if more than one element is found. If no element is found, a new search is performed which allows partial matches. If that search returns multiple matches, an error is raised.  prefer_exact: If multiple matches are found, some of which are exact, and some of which are not, then the first exactly matching element is returned. NOTE: The default value for Capybara.match is :smart
  • 43. Capybara hooks  Hooks with cucumber tags Capybara uses hooks to run setup and teardown for the test cases. hooks adds the before test and after test scenarios.  Before hook: It is used as setup for test case.  After hook: It is used as teardown for test case. NOTE: @fileUpload and @fileDownload are cucumber tags.
  • 44. Cucumber Command line options  Cucumber command line You can check the available command line options in cucumber with command: “cucumber –help”. Below are some of the useful options.  --require : Require files before executing the features. If this option is not specified, all *.rb files that are siblings or below the features will be loaded auto-matically. Automatic loading is disabled when this option is specified, and all loading becomes explicit. Files under directories named "support" are always loaded first.  --format : How to format features. Available formats:  Debug  Html  Json  Pretty NOTE: The default value for --format is pretty.
  • 45. Cucumber Command line options  Cucumber command line (Continue) You can check the available command line options in cucumber with command: “cucumber –help”. Below are some of the useful options.  --out : Write output to a file/directory instead of STDOUT. This option applies to the previously specified –format. e.g –out report.html  --tags : Only execute the features or scenarios with tags matching. e.g – tags @login  --dry-run : Invokes formatters without executing the steps. Check for test steps if they are implemented or not. NOTE: You can check the available formats functionality by with help option.
  • 46. Cucumber Test Execution and Reporting  Cucumber Execution  Command to execute all cucumber tests : Open the command prompt and locate to features directory and type “cucumber” press enter. It will execute all the cucumber test scenarios alphabetically.  Command to execute tests with specific tag : run command “cucumber –tags @login” this will only execute scenarios with login tag.  Command to execute tests and generate html reports : Run command : “cucumber –tags @login –format html –out report.html” this will execute scenarios with login tag and generate a report.html file in same directory from where the tests have been executed.