Using Capybara To Automate Web Tasks

Capybara is primarily used for testing, but did you know it has other uses?


Published on:July 1, 2016

Introduction

Capybara is widely for being used along with a testing framework, but you don't actually have to use Capybara with a test framework. Instead, you can use Capybara's DSL to do things like automate sign up forms or perform searches. You can even use it to crawl an entire site! In this article we will cover a simple example of using Capybara to perform a search on this very site. Let's get started.

Initial Setup

The first thing we need to do is create a Gemfile that will install the gems we need. Create a gemfile in a new directory and add in the code listed below.

Gemfile:

# frozen_string_literal: true

source 'https://rubygems.org'

gem 'capybara'
gem 'selenium-webdriver'

Now, run bundle to install the gems:

Terminal Commands:

bundle

Great! Now let's get started with our script.

Writing the script

To write our script, create a new ruby file and in the code listed below. I named my script `automate.rb`, but you can call it whatever you like.

automate.rb:


# frozen_string_literal: true

require 'capybara'
require 'capybara/dsl'

Capybara.run_server = false
Capybara.current_driver = :selenium

module RichOnRails
class Search
include Capybara::DSL

def initialize(search_term)
visit 'https://richonrails.com'
fill_in 'Search', with: search_term
find('#q_title_cont').send_keys :enter
find 'h1', text: "Search Results for \"#{search_term}\""
Capybara.save_screenshot
end
end
end

response = RichOnRails::Search.new('capybara')

This file defines a module called RichOnRails that contains a class called Search. The class has a constructor that takes a search term and saves a screenshot of the page.

Let's take a closer look at what's inside.

  • Line 11 includes the capybara DSL within the class. This enables methods such as fill_in and find.
  • Line 14-15 tells Capyabara to open the RichOnRails.com website and fill in the search box with 'capybara'.
  • Line 16 sends the enter key. This is because the submit button is not visible. NOTE: This is a known issue with my site and will be addressed in the future along with a bunch of other issues.
  • Line 17 ensures that the search results page is displayed. The `assert_selector` is one of many assertions that capybara provides. Note that If the element on a page does not exist, capybara will wait a certain amount of seconds for it to appear.
  • Line 18 saves a screenshot of the page to the current directory.

Conclusion

I hope this article gave you a sneak peak into what Capybara is capable of and what it can be used for. If you have any feedback, please feel free to leave a comment below. That's it! Thanks for your support and thanks for reading!