0

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 ?

  • 2
    A reminder to downvoters that self-answered questions are not only allowed, but encouraged! Experts who run into problems and then shares how they're solved is a good thing! – corsiKa Apr 24 '19 at 16:12
1

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 = File.open('locators.yml')
        pairs = []
        keys = []
    
        locators_file.each_line do |line|
          words = line.split(': ')
          pairs << {words[0] => words[1]}
          keys << words[0]
        end
        locators_file.close
    
        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
        end
        unused_keys_exist = unused_keys.size > 0
        if unused_keys_exist
          p "Unused Page Object keys! Please address these orphans:"
          p unused_keys
        end
    
        expect(unused_keys_exist).not_to be, 
          lambda {"Failure - orphan page object identifiers #{unused_keys}"}    
      end
    
      def search_file_for_key(file, key)
        spec_file = File.open(file)
        file_contents = spec_file.read
        spec_file.close
        @key_used = true if file_contents.match(/#{key}/)
      end
    
    end
    
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.