Skip to content

Instantly share code, notes, and snippets.

@mcmire
Last active May 24, 2016 19:05
Show Gist options
  • Select an option

  • Save mcmire/c6e9c080998cd95f1787918a86e1e17a to your computer and use it in GitHub Desktop.

Select an option

Save mcmire/c6e9c080998cd95f1787918a86e1e17a to your computer and use it in GitHub Desktop.
Making a page object class for use in feature tests

Feature tests can oftentimes get long, complicated, and hard to maintain. One common strategy that I use to break them apart is to use "page object classes". These classes may contain methods to find elements on the page, methods to interact with those elements, and methods to make assertions about what the user sees after those interactions are made.

This gist demonstrates what these page object classes look like. One thing to note is that Capybara methods like find and RSpec methods such as expect are automatically available in the class. This is made possible by having the class inherit from SimpleDelegator and then having the test pass self to the class initializer when an object is created. self is the context in which the test is running, and by receiving it, the page object can access method that the feature test can access. Now, there's a second way you could accomplish this: you could include RSpec::Matchers and Capybara::DSL instead of inheriting from SimpleDelegator. But this approach has one downside, which is applicable if you've configured RSpec to include custom modules in your feature tests. In this case, the functionality those modules provide won't be available in your page object class, because that class isn't a feature example group class.

module Features
class MyPageObjectClass < SimpleDelegator
def some_container_element
find(".whatever")
end
def expect_to_do_something
expect(page).to have_css(".something")
end
end
end
require "rails_helper"
feature "Some great feature" do
scenario "Some awesome scenario" do
my_page = Features::MyPageObjectClass.new
within my_page.some_container_element do
# do something
end
my_page.expect_to_do_something
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment