Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Rails Capybara Setup

DZone's Guide to

Rails Capybara Setup

We look at how Capybara helps web developers create automated tests for their Ruby on Rails web applications. Read on to get started!

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Capybara is a web-based automation framework tool for testing Rails apps. It helps you to create functional tests that simulate how users would interact with your application through the browser.

It is a fantastic tool for testing your application through the browser!

Capybara doesn't interact with the website, it's just a layer between you and the web driver. For this, you can use Selenium web driver or any of the other drivers that Capybara supports.

Configuring Capybara

Capybara can easily integrate with common test frameworks used in Rails. It is mostly used together with RSpec for writing features and, but less commonly, controller tests.

Before you get started, you need to add the following gems to the :test group in your Gemfile and run bundle install:

group :test do
  gem 'capybara'
  gem 'selenium-webdriver'
end

Testing With Capybara

Capybara comes with a user-friendly DSL ( Domain Specific Language), which offers helper methods for extracting information, inputting data, testing, or clicking around.

By default, Capybara will only locate visible elements. This is because a real user would not be able to interact with non-visible elements. You can read more about this at rubydoc.info.

Common DSL Options

Here we will cover the most commonly used DSL actions for interacting with elements in your web application:

Find specific elements and manipulate them:

find_field('field_name').value
find_field(id: 'field_id').value
find_link('link_name', visible: all).visible?
find_button('button_name').click

This is one of the most important functions every good programmer should know if you want to manipulate your elements. You can use it to find your links, buttons, and fields and check if they are visible to the user, or click on them. Find will always wait for an element to appear on the page before raising an error.

Interact with the web application by following links and buttons:

click_link('link_id')
click_link('link_text')
click_button('button_name')
click_on('link_text') # clicks on either link or button

Always use one of these options when you want to access a link or a button. You can do this by using id, title, text within a tag, or value of the element.

Interact with form elements:

fill_in('Title', :with => 'Example')
choose('radio_button')
check('checkbox')
uncheck('checkbox')
attach_file('image', 'image_path') # upload a file
select('option', from: 'select_box') # select from dropdown

Whenever you want to fill up your form you should use one of these possibilities. Depending on the type of the element the present values are: id, name, or related label element. The only exception is attach_file, it can only accept id and name.

Navigate through pages with:

visit('url_name') 

You can easily navigate through pages with this simple command or only access the current page with:

expect(page).to have_current_path(path_name) 

Query the page for the existence of certain elements:

expect(page).to have_selector('table tr') 
expect(page).to have_content('content_name') 

Restrict certain actions within a specific area of the page with scoping:

# within(:xpath, 'actual_xpath') do
  fill_in 'Title', with: 'Example'
end

Use the within method when you want to use actions only in a specific area or use these special methods: within_fieldset for a specific fieldset and within_table for a specific table.

Debug with the following methods:

save_and_open_page # current snapshot of the page
save_sceenshot('screenshot_name.png')
save_and_open_screenshot # saves and automatically opens the screenshot

When you want to save the snapshot of the page, just add one of these lines to your code, or you can also retrieve the current state of an element with:

print page_name.html 

Matchers

When trying to find an element by using the DSL or XPath, it is common to have two or more matches. You can customize the way Capybara find elements by using:

  • Capybara.exact - Finds exact matches of an element.
  • Capybara.match - Controls how Capybara behaves when multiple elements match.

To avoid getting an Ambiguous match error when more than one match is found, you should consider using the following matching strategies supported by Capybara:

  • :first - This will simply pick the first element that matches.
  • :one - This will raise an error if more than one element is found.
  • :prefer_exact - This finds all matching elements but only the first exactly matching element is returned and the rest are discarded.
  • :smart - If Capybara.exact is set to true, it will behave like :one. Otherwise, it will try to find the exact element. Once again, an error is raised if multiple elements are found. If no element is found, a new search is performed.

JavaScript and Asynchronous Calls

Asynchronous JavaScript allows you to interact with an element on the page that isn't present yet. This can happen when using JavaScript to creates a new element on the page:

click_link('test')
click_link('foo') 

Once you click on the 'test' link it will trigger an asynchronous process, which will show the 'foo' link. Clicking on the 'foo' will most likely raise an error since that link doesn't exist yet.

Capybara can handle this by waiting for a brief period of time. You can adjust the default waiting period (the default is 2 seconds) with: Capybara.default_max_wait_time.

Capybara and RSpec

Using Capybara together with RSpec is as simple as adding require 'capybara/rails' in the rspec_helper.rb file. To be able to do this, you will need RSpec installed beforehand.

describe 'users' do
  let! :each do
    @user = FactoryGirl.create(:user)
    login_as(@user)
  end

  describe GET user#edit' do
    it 'should update user' do
      visit edit_user_path(@user)
      within('#edit_user_path') do
        fill_in 'email', with: 'john@example.com'
      end
      click_button 'Save'
      find_button('Save').click
      expect(page).to have_content 'Success'
    end
  end
end

This was a simple example that shows how you can use Capybara and RSpec at the same time by editing the user.

Hope this article helped you understand what Capybara can do for your test environment!

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
web dev ,ruby on rails ,capybara

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}