Rails Testing — Interactive Capybara Console


The scenario

Often when working on a mature web app you’ll be tasked with adding new functionality to existing infrastructure. If that infrastructure is front-end in nature and relies heavily on JavaScript you’ll have the task of writing or updating browser tests for your code.

Here’s a trivial code example

The purpose of these tests are fairly straightforward.

* setup :prep_test_data — this does just what it sounds like via FactoryGirl, fixtures, etc… * Next we verify the expected greeting exists to the user * Then we open up a modal dialog and start clicking around in our app to see if panels are rendering as expected

tag: tech
Good JavaScript & CSS will significantly simplify the authoring of browser tests because you can write code like this:

But what do you do when you’ve got code like this to target?

go ahead, write that xpath statement

If you take close look, this code is largely generated so the id’s can’t be used as reference as they’re different every time. Which means Capybara is going to need to target elements using either named elements, XPath, or CSS selectors (utilizing id’s whenever possible).

Load Capybara via Rails Console

As simple as this is, it saves me a ton of time when writing new browser tests. Let me show you how to use it.

First off, you need to start your rails app using your test database.

$ RAILS_ENV=test rails server

Save this gist to your project (I put mine in /test/capybara_irb.rb) and load it from Rails console like so.

go ahead, write that xpath statement

Once you’ve got this code running you should have an instance of Firefox open (being remote controlled by WebDriver), a Rails console running, and your test database setup with the data required to browse, click, make assertions about content, and verify a host of different interactions with your app.

Kudos to jnicklas (and friends) for their great work with Capybara.

HiringThing

Author: HiringThing

HiringThing is easy to use, intuitive online recruiting software that makes it easy to post jobs online, manage applicants and hire great employees.