SlideShare a Scribd company logo
1 of 47
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

More Related Content

What's hot

Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3day
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
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
 
What’s new in laravel 9
What’s new in laravel 9What’s new in laravel 9
What’s new in laravel 9Katy Slemon
 
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?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?Julian Robichaux
 
Maven 3 Overview
Maven 3  OverviewMaven 3  Overview
Maven 3 OverviewMike Ensor
 
How to dockerize rails application compose and rails tutorial
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 tutorialKaty Slemon
 
Preparing your code for Java 9
Preparing your code for Java 9Preparing your code for Java 9
Preparing your code for Java 9Deepu Xavier
 
Mete Atamel
Mete AtamelMete Atamel
Mete AtamelCodeFest
 
Deploying Symfony | symfony.cat
Deploying Symfony | symfony.catDeploying Symfony | symfony.cat
Deploying Symfony | symfony.catPablo Godel
 
Maven plugins, properties en profiles: Advanced concepts in Maven
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 MavenGeert Pante
 
Dynamic Languages Web Frameworks Indicthreads 2009
Dynamic Languages Web Frameworks Indicthreads 2009Dynamic Languages Web Frameworks Indicthreads 2009
Dynamic Languages Web Frameworks Indicthreads 2009Arun Gupta
 
Short Lived Tasks in Cloud Foundry #cfdtokyo
Short Lived Tasks in Cloud Foundry #cfdtokyoShort Lived Tasks in Cloud Foundry #cfdtokyo
Short Lived Tasks in Cloud Foundry #cfdtokyoToshiaki Maki
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on RailsAgnieszka Figiel
 
Workflow automation for Front-end web applications
Workflow automation for Front-end web applicationsWorkflow automation for Front-end web applications
Workflow automation for Front-end web applicationsMayank Patel
 
Leave end-to-end testing to Capybara
Leave end-to-end testing to CapybaraLeave end-to-end testing to Capybara
Leave end-to-end testing to CapybaraHiroshi SHIBATA
 

What's hot (20)

Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3
 
Maven Introduction
Maven IntroductionMaven Introduction
Maven Introduction
 
How DSL works on Ruby
How DSL works on RubyHow DSL works on Ruby
How DSL works on Ruby
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
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
 
What’s new in laravel 9
What’s new in laravel 9What’s new in laravel 9
What’s new in laravel 9
 
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?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
 
Maven 3 Overview
Maven 3  OverviewMaven 3  Overview
Maven 3 Overview
 
How to dockerize rails application compose and rails tutorial
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
 
Preparing your code for Java 9
Preparing your code for Java 9Preparing your code for Java 9
Preparing your code for Java 9
 
Mete Atamel
Mete AtamelMete Atamel
Mete Atamel
 
Maven 2 Introduction
Maven 2 IntroductionMaven 2 Introduction
Maven 2 Introduction
 
How Flipkart scales PHP
How Flipkart scales PHPHow Flipkart scales PHP
How Flipkart scales PHP
 
Deploying Symfony | symfony.cat
Deploying Symfony | symfony.catDeploying Symfony | symfony.cat
Deploying Symfony | symfony.cat
 
Maven plugins, properties en profiles: Advanced concepts in Maven
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
 
Dynamic Languages Web Frameworks Indicthreads 2009
Dynamic Languages Web Frameworks Indicthreads 2009Dynamic Languages Web Frameworks Indicthreads 2009
Dynamic Languages Web Frameworks Indicthreads 2009
 
Short Lived Tasks in Cloud Foundry #cfdtokyo
Short Lived Tasks in Cloud Foundry #cfdtokyoShort Lived Tasks in Cloud Foundry #cfdtokyo
Short Lived Tasks in Cloud Foundry #cfdtokyo
 
Maven
MavenMaven
Maven
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
 
Workflow automation for Front-end web applications
Workflow automation for Front-end web applicationsWorkflow automation for Front-end web applications
Workflow automation for Front-end web applications
 
Leave end-to-end testing to Capybara
Leave end-to-end testing to CapybaraLeave end-to-end testing to Capybara
Leave end-to-end testing to Capybara
 

Similar to Capybara and cucumber with DSL using ruby

Behavioural Testing Ruby/Rails Apps @ Scale - Rspec & Cucumber
       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
 
Integration and Acceptance Testing
Integration and Acceptance TestingIntegration and Acceptance Testing
Integration and Acceptance TestingAlan Hecht
 
Instruments ruby on rails
Instruments ruby on railsInstruments ruby on rails
Instruments ruby on railspmashchak
 
Jaoo Michael Neale 09
Jaoo Michael Neale 09Jaoo Michael Neale 09
Jaoo Michael Neale 09Michael Neale
 
Installing spark scala console in windows 10
Installing spark scala console in windows 10Installing spark scala console in windows 10
Installing spark scala console in windows 10Ankit Kaneri
 
End-to-end web-testing in ruby ecosystem
End-to-end web-testing in ruby ecosystemEnd-to-end web-testing in ruby ecosystem
End-to-end web-testing in ruby ecosystemAlex Mikitenko
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technologyMinal Maniar
 
Play Support in Cloud Foundry
Play Support in Cloud FoundryPlay Support in Cloud Foundry
Play Support in Cloud Foundryrajdeep
 
Functional Scala 2022 - scalajs Alexis.pdf
Functional Scala 2022 - scalajs Alexis.pdfFunctional Scala 2022 - scalajs Alexis.pdf
Functional Scala 2022 - scalajs Alexis.pdfssusercd195b
 
Viridians on Rails
Viridians on RailsViridians on Rails
Viridians on RailsViridians
 
Ruby on rails integration testing with minitest and capybara
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 capybaraAndolasoft Inc
 
COP_RoR_QuArrk_Session_Oct_2022.pptx
COP_RoR_QuArrk_Session_Oct_2022.pptxCOP_RoR_QuArrk_Session_Oct_2022.pptx
COP_RoR_QuArrk_Session_Oct_2022.pptxNitesh95975
 

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

Behavioural Testing Ruby/Rails Apps @ Scale - Rspec & Cucumber
       Behavioural Testing Ruby/Rails Apps @ Scale - Rspec & Cucumber       Behavioural Testing Ruby/Rails Apps @ Scale - Rspec & Cucumber
Behavioural Testing Ruby/Rails Apps @ Scale - Rspec & Cucumber
 
Integration and Acceptance Testing
Integration and Acceptance TestingIntegration and Acceptance Testing
Integration and Acceptance Testing
 
TorqueBox
TorqueBoxTorqueBox
TorqueBox
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
 
Basic RSpec 2
Basic RSpec 2Basic RSpec 2
Basic RSpec 2
 
Instruments ruby on rails
Instruments ruby on railsInstruments ruby on rails
Instruments ruby on rails
 
Jaoo Michael Neale 09
Jaoo Michael Neale 09Jaoo Michael Neale 09
Jaoo Michael Neale 09
 
Rspec
RspecRspec
Rspec
 
Cucumber
CucumberCucumber
Cucumber
 
Installing spark scala console in windows 10
Installing spark scala console in windows 10Installing spark scala console in windows 10
Installing spark scala console in windows 10
 
End-to-end web-testing in ruby ecosystem
End-to-end web-testing in ruby ecosystemEnd-to-end web-testing in ruby ecosystem
End-to-end web-testing in ruby ecosystem
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Play Support in Cloud Foundry
Play Support in Cloud FoundryPlay Support in Cloud Foundry
Play Support in Cloud Foundry
 
Functional Scala 2022 - scalajs Alexis.pdf
Functional Scala 2022 - scalajs Alexis.pdfFunctional Scala 2022 - scalajs Alexis.pdf
Functional Scala 2022 - scalajs Alexis.pdf
 
Aspose pdf
Aspose pdfAspose pdf
Aspose pdf
 
Dev streams2
Dev streams2Dev streams2
Dev streams2
 
Intro to Sails.js
Intro to Sails.jsIntro to Sails.js
Intro to Sails.js
 
Viridians on Rails
Viridians on RailsViridians on Rails
Viridians on Rails
 
Ruby on rails integration testing with minitest and capybara
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
 
COP_RoR_QuArrk_Session_Oct_2022.pptx
COP_RoR_QuArrk_Session_Oct_2022.pptxCOP_RoR_QuArrk_Session_Oct_2022.pptx
COP_RoR_QuArrk_Session_Oct_2022.pptx
 

Recently uploaded

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 

Recently uploaded (20)

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 

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.