rubyseleniumcapybarapageobjectspage-object-gem

How do I reference the Capybara driver for creating my pageobjects/specs.


I am attempting to use pageobjects along with with my Capybara specs but can't seem to properly reference the driver. Basically I want to be able to use the PageObjects to define the fields on the page (this is login_page.rb), but when I try to create the object in the spec, it is throwing errors with saying that the object is nil.

spec_helper.rb:

# frozen-string-literal: true

require 'rspec'
require 'capybara/rspec'
require 'capybara/dsl'
require 'selenium-webdriver'
require 'page-object'


# loading page object files
page_paths  = File.join(Dir.pwd, 'spec', 'pages', '**', '*.rb')
puts 'foo'
Dir.glob(page_paths).each { |file| puts file}
Dir.glob(page_paths).each { |file| require file }

Capybara.register_driver :firefox do |app|
  Capybara::Selenium::Driver.new(app, browser: :firefox)
end

Capybara.default_driver = :firefox
Capybara.app_host = *********** #redacted
Capybara.default_max_wait_time = 5

RSpec.configure do |config|
  config.before(:all) do
    @browser =  Capybara::Selenium::Driver
  end

  config.before(:each) do
    config.include Capybara::DSL
  end
end

login_page.rb

class LoginPage
  include Capybara::DSL
  include PageObject

  text_field(:username, id: 'username')
  text_field(:password, id: 'password')
  button(:login, id: 'loginButton')

  def initialize(driver)
    @driver = driver
  end
end

login_spec.rb

require 'spec_helper'

describe 'On Login page' do
  context 'using proper password' do
    before(:each) do
      visit('/')
    end

    it 'logs in as foo' do
      login_page = LoginPage.new(@browser)
      login_page.username = 'foo'
      login_page.password = 'bar'
      login_page.login
    end
  end
end

Solution

  • Assuming you're talking about the page-object gem - https://github.com/cheezy/page-object - it doesn't support Capybara, it supports watir-webdriver/watir and selenium-webdriver. Additionally Capybara::Selenium::Driver is a class not an object instance. As shown in the page-object readme you need to pass an object instance into your page objects constructor

    @browser = Selenium::WebDriver.for :firefox
    

    If you want a page object framework that supports Capybara you may want to look at something like site-prism instead.