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 0.4.1.2 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,
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 = HomePage.new(Capybara.current_session)
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).
URL = "/"
@session = session
@session.fill_in("Description", :with => description)
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.