Page Model with Cucumber and Capybara

I’ve spent some time today changing the Cucumber/Capybara tests in one of my pet projects to use a page model. Since I didn’t find much stuff on the interwebs about it, why not write it here ?

The idea behind having a page model is to keep steps related to a specific page on your app in the same place, so you can reduce the repetition of steps in different tests. Is definitely not a complicated practice, and setting Capybara for it is a simple step.

Setting the context, Im using Cucumber 0.10 with Capybara and Rails 3.0.1. Have done the standard installation steps recommended by the cucumber-rails github page.

The only modification I’ve made with the created structure is adding a folder for the page objects, so the final structure is this:

As you can see, inside the pages folder there is a home page file, which is responsible for every action/assertion related to the home page.

Nothing new with the cucumber features, which keep having it’s standard style

Feature: Manage tasks
In order to manage my tasks,
a user
wants to create tasks in different categories

Scenario: Create a new task
Given I am in the Do Me home page
When I create an urgent and important task with description "my task"
Then I should see "my task" in the "Urgent and Important" section

However, in order to create our page object, we need to inject the test driver on it, which in Capybara’s case, is the session object.

Given /^I am in the home page$/ do
@home_page =

When /^I create an urgent and important task with description "([^"]*)"$/ do |task_description|

And from there is just the trouble of creating the page class (or do like me, who shamelessly copied the style from here).

class HomePage

URL = "/"

def initialize(session)
@session = session

def visit
@session.visit URL

def fill_task_description(description)
@session.fill_in("Description", :with => description)

def check_urgent

def check_important

def create_task
@session.click_button("Create Task")

And that's pretty much it, now is just choosing your preferred driver and run the tests. As you can see, not much effort for a nice improvement.

  1. Andrew K. said:

    Wonderful, thank you for posting.
    I was using all sorts of hacks to use the Page Object pattern with my cuke+capybara tests, Capybara.current_session was what I was missing.

    • Hi Nat,

      that’s great, will definitely check it out!