Master Web Automation with Capybara & Selenium

Learn how to use Capybara and Selenium for efficient web automation testing, covering setup, configuration, and best practices

Get Started free
Getting Started with Capybara & Selenium for Web Testing
Home Guide Getting Started with Capybara & Selenium for Web Testing

Getting Started with Capybara & Selenium for Web Testing

Selenium with Capybara is a powerful combination for creating robust test automation framework for Web Application. Capybara provides Intuitive DSL(Which mimics the language of an actual user) and is written in Ruby.

Capybara is agnostic about the driver running your tests and comes with Rack::Test and Selenium support built in. WebKit is supported through an external gem.

Overview

Why Use Capybara and Selenium for Web Automation?

  • Intuitive and Readable Tests: Capybara’s domain-specific language (DSL) makes tests easy to write and understand.
  • Simulates Real User Behavior: Selenium mimics actual user interactions with browsers, ensuring tests reflect real-world usage.
  • Powerful Synchronization: Capybara automatically handles waits for asynchronous processes, eliminating manual waits in your tests.
  • Integration with RSpec and Cucumber: Capybara integrates easily with Ruby testing frameworks like RSpec and Cucumber.

Getting Started with Capybara and Selenium

  • Prerequisites: Install Ruby, set up an IDE like VS Code, and use Bundler to manage dependencies.
  • Installation: Add required gems (capybara, selenium-webdriver, rspec) to the Gemfile and run bundle install.
  • Write Your First Test: Use Capybara DSL to visit a site, perform actions, and assert behavior using RSpec for validation.

This article explains on what is Capybara and how to use it with Selenium.

What is Capybara?

Capybara is a testing library that is widely used for end-to-end web application testing and is ruby-based. Capybara comes with built-in support forSupport to selenium, so that user can just mention the driver in the test and it’s ready to use.

Below is the example of how the test looks using capybara

require ‘capybara/dsl’
Capybara.default_driver = :selenium_chrome # Uses Chrome browser

class GoogleSearch
include Capybara::DSL

def search
visit ‘https://www.google.com’
fill_in ‘q’, with: ‘Capybara Selenium’
find(‘input[name=”btnK”]’).click
sleep 2 # Wait to see the result
end
end

GoogleSearch.new.search

What is Selenium?

Selenium is a very popular test automation framework used for automating web based applications. Selenium comes with various browser drivers which will interact with Real browsers by sending the commands.

Selenium supports all below browsers

  • Google Chrome
  • Mozilla Firefox
  • Microsoft Edge
  • Safari
  • Opera

Selenium supports all the below languages

  • Python
  • Java
  • C#
  • Javascript/Typescript
  • Ruby
  • Kotlin

Why use Capybara and Selenium for Web Automation Testing?

Capybara with selenium is a powerful combination which provides below key advantages

  • Test written are Easy to write and Read: Capybara provides intuitive DSL for defining tests and those tests will have actions integration from Selenium
  • Simulates User Behavior: Selenium mimics real time user interaction with Browser, this ensures that tests written are simulating the real time user journey
  • Powerful synchronization: Capybara provides this feature to automatically wait for asynchronous processes to complete and you don’t need to add manual wait
  • Works with RSpec, Cucumber: Capybara provides easy way of integrating with popular ruby testing frameworks.

Get Started with Capybara and Selenium for Web

Get started by setting up the required things to run the Capybara with Selenium

Prerequisites

  1. Ruby
  2. IDE(VS Code)

To install ruby run below command (macos)

brew install ruby

Next install the bundler, bundler will manage the gems

gem install bundler

Now you can create the project folder where the tests will reside. Once the folder is created execute below command from the root of the folder

bundle init

This will create a gem file. A gem file is where you add all the dependencies required for the project

Open the Gem file and paste the below

source ‘https://rubygems.org’gem ‘capybara’
gem ‘selenium-webdriver’
gem ‘rspec’

you are adding three dependencies here: capybara, selenium-webdriver and rspec.

Save the gem file and run the below command to install the gems

bundle install

Talk to an Expert

How Capybara and Selenium Work Together

Capybara provides the users to write tests in intuitive DSL(Domain-Specific Language) and selenium will be used as a driver, which will run actions in the real web browsers like Chrome, Firefox or Edge.

Capybara also provides an assertion to validate expected behavior.

Automate Banner

Writing Your First Test with Capybara and Selenium

Write your first test using capybara and selenium. Use BrowserStack’s Demo site for creating a scenario for the test.

In the project create a new file called bstackDemoTest.rb

In the newly created file, add the imports first

require ‘capybara/dsl’require ‘rspec’

Define the driver you are going to use, in the case it will be selenium

Capybara.default_driver = :selenium_chrome

Next step is to define the class and function which will contain the actions

class BstackDemo include Capybara::DSL
include RSpec::Matchers

def validateNavigationHeader
visit ‘https://bstackdemo.com/’
expect(find(‘#favourites strong’)).to have_content(‘Favourites’)
sleep 2 # Wait to see the result before the script exits
end
end

BstackDemo.new.validateNavigationHeader

Inside the class specify to include two modules

include Capybara::DSL include RSpec::Matchers

The module Capybara::DSL is included to support the DSL style of writing test and RSpec::Matchers will allow us to write assertion for the tests

def validateNavigationHeader visit ‘https://bstackdemo.com/’
expect(find(‘#favourites strong’)).to have_content(‘Favourites’)
sleep 2 # Wait to see the result before the script exits
end
End

In the above code block you are defining the method validateNavigationHeader which contains all the actions that has to be performed inside browser

Perform two actions in the above test

  1. Visiting BrowserStack’s Demo site
  2. Finding the navigation link and validating its content

Sleep of 2 seconds is optional and only for the demonstration purpose, to see the result in the browser.

Save the file and execute the below command to run the test

ruby bstackDemoTest.rb

Best Practices for Testing with Capybara and Selenium

Best practices will ensure that tests will be reliable, Stable, Maintainable and Efficient.

  • Write Structured Tests : Do not write plain ruby tests, instead use RSpec for writing and organising tests. Below is the test written with RSpec
require ‘capybara/rspec’
Capybara.default_driver = :selenium_chrome

RSpec.describe ‘Google Search’, type: :feature do
it ‘performs a search’ do
visit ‘https://bstackdemo.com/’
expect(find(‘#favourites strong’)).to have_content(‘Favourites’)
sleep 2 # Wait to see the result before the script exits
end
end

  • Use Dynamic wait instead of Hardcoded waits : Capybara can automatically wait for the elements
expect(find(‘#favourites strong’,wait: 20)).to have_content(‘Favourites’)
  • Always run tests in headless mode : Running in headless mode will always be faster. If it’s CI or bulk test execution, run them in headless mode. the example code to run in headless mode will look like below
require ‘capybara/rspec’require ‘selenium-webdriver’

Capybara.register_driver :headless_chrome do |app|
options = Selenium::WebDriver::Chrome::Options.new
options.add_argument(‘–headless’)
options.add_argument(‘–disable-gpu’)
options.add_argument(‘–window-size=1280,800’)
Capybara::Selenium::Driver.new(app, browser: :chrome, options: options)
end

Capybara.default_driver = :headless_chrome

RSpec.describe ‘Google Search’, type: :feature do
it ‘performs a search’ do
visit ‘https://bstackdemo.com/’
expect(find(‘#favourites strong’,wait: 20)).to have_content(‘Favourites’)
sleep 2 # Wait to see the result before the script exits
end
end

  • Session clean up after each test: Resetting the session after each test execution will ensure that tests are not dependent on each other and there is no test data leak across. Every test should be able to execute independently. This can be achieved using below code
RSpec.configure do |config| config.after(:each) do
Capybara.reset_sessions!
end
end

Why choose BrowserStack to run Selenium Tests?

Here are some reasons why you might choose BrowserStack Automate to run Selenium tests:

1. Cross-Browser and Cross-Platform Testing: BrowserStack provides access to a wide range of real devices, browsers, and OS combinations. This allows you to run your Selenium tests across various environments without needing to set up the infrastructure yourself.

2. Real Device Testing: Unlike emulators, BrowserStack offers real devices for testing. This ensures more accurate results, simulating how the application performs on actual user devices.

3. No Infrastructure Management: With BrowserStack Automate, you don’t have to worry about maintaining physical or virtual machines for testing. It handles the entire infrastructure, saving time and effort.

4. Instant Access to Browsers & Devices: You can quickly run tests on the latest browser versions, and as new versions are released, BrowserStack updates their platform automatically.

5. Parallel Test Execution: Run multiple tests in parallel, which speeds up the testing process significantly. This helps in cutting down the time required for regression or functional testing.

6. Scalability: BrowserStack offers scalable solutions, allowing you to run tests on a large number of devices and browsers simultaneously, without worrying about server overload or limitations.

7. Integration with CI/CD Tools: BrowserStack integrates easily with CI/CD tools like Jenkins, Travis CI, CircleCI, and GitHub Actions. This makes it simple to automate your testing pipeline and ensure continuous delivery.

8. Geolocation Testing: Test your web applications from different geographical locations to simulate various user experiences, helping to ensure your application works optimally worldwide.

9. Real-Time Debugging: BrowserStack provides detailed logs, screenshots, and video recordings for each test run. This makes debugging easier and faster, especially when working on complex issues.

10. Support for Various Automation Frameworks: Besides Selenium, BrowserStack supports various testing frameworks, such as Appium, Cypress, and Playwright, providing flexibility in test execution.

Try BrowserStack Automate

Conclusion

You have seen how quicker it is to set up Capybara with selenium and how to execute the tests. Capybara and Selenium is a powerful combination to write automated tests for web applications, Capybara providing intuitive DSL and Selenium providing capability to interact with Real browsers.

Tags
Automation Testing Capybara Selenium

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord