How can I test if a page object yml file has orphaned keys using rspec?

  • I like using page objects through a yaml file with name:locator pairs

    One problem I run into is that over time as the locators file grows, test cases are changed or removed and we end up with duplicates and orphans.

    Is there any way to test if page objects stored this way are being used or are orphans through automated testing ?

  • You can write an RSpec test that tries to do this by grepping spec files for the locator names. It will not be foolproof. Some orphans might slip through and the test still passes (falsely). However if the locator is not found anywhere it does indicate an orphan and it will fail the test.

    This is based on:

    • locators being in a locators.yml file
    • locator file format is name : 'locator_string' per line
    • spec file having the format *_spec.rb
    • specs in subdirectories are supported (through glob)

      require 'rspec'
      describe 'Page Objects locator yml file' do
        it "uses all its locator keys" do
          locators_file ='locators.yml')
          pairs = []
          keys = []
          locators_file.each_line do |line|
            words = line.split(': ')
            pairs << {words[0] => words[1]}
            keys << words[0]
          files = Dir.glob("**/*_spec.rb")
          unused_keys = []
          keys.each do |key|
            @key_used = false
            files.each {|file| search_file_for_key(file, key) }
            unused_keys << key unless @key_used
          unused_keys_exist = unused_keys.size > 0
          if unused_keys_exist
            p "Unused Page Object keys! Please address these orphans:"
            p unused_keys
          expect(unused_keys_exist).not_to be, 
            lambda {"Failure - orphan page object identifiers #{unused_keys}"}    
        def search_file_for_key(file, key)
          spec_file =
          file_contents =
          @key_used = true if file_contents.match(/#{key}/)

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2