LAGUREN.NET
  • HOME
  • About Me

Using Metaprogramming Instead of Ifs or Case Statements in Automation

4/20/2014

 
Picture
At one time or another, an automation engineer has written the following ruby code below to select a menu option above.
def select_menu(choice)
  if choice == 'Users'    within(:xpath, ".//*[@'navbar-inner']//*[@'nav'])"
      click_on('Users')
    end
  elsif choice == 'Apps'
    within(:xpath, ".//*[@'navbar-inner']//*[@'nav'])"
      click_on(''Apps')
    end
  elsif choice == 'Activity'
    within(:xpath, ".//*[@'navbar-inner']//*[@'nav'])"
      click_on('Activity')
    end
  elsif choice == 'Settings'
    within(:xpath, ".//*[@'navbar-inner']//*[@'nav'])"
      click_on('Settings)
    end
  else
    $log.debug("Invalid Choice")
    exit 1
  end
end
 
Although this code works, maintenance can soon become a time consuming effort.  
  1. If another menu option is added, another elsif will need to be added along with the within method
  2. If the xpath of the menu bar where to change, then all the if/elsif statements would need to be update.

Thanks to metaprogramming, a more elegant and maintainable solution can now be written:
  ["Users", "Apps", "Activity", "Settings"].each do |menu|
    define_method("select_#{menu}") do
      within(:xpath, ".//*[@'navbar-inner']//*[@'nav']) do
        click_link("#{menu}")
      end
    end
  end


Metaprogramming is the act of writing code that operates on code rather than on data.  The define_method allows one to create methods programmatically using a method.  The 'def' method is not needed in this case.

In the newly rewritten code, ruby will now create 4 methods:
  • select_Users
  • select_Apps
  • select_Activity
  • select_Settings

This addresses the two maintenance issues pointed out earlier.  
  1. Adding or removing a menu option is as simple as adding/removing an element in the given array, ["Users", "Apps", Activity", "Settings"]
  2. Updating the location of the menu bar to query within is limited to one line

Additionally, if a menu is not defined, then there would not be an existing method.  This eliminates the need to have the else statement to handle the case of entering a menu option that does not exist.

Checkout the Page Objects created for OneLogin.
Forward>>

    RSS Feed

    Categories

    All
    Advice
    Agile
    Android
    Automation
    BDD
    C9D9
    Capybara
    Career
    Continuous Delivery
    Continuous Integration
    Cucumber
    Database
    Ebates
    Firefox
    Fiverr
    GIT
    Groupon
    Interview
    Investing
    Jenkins
    JIRA
    Jmeter
    Jobs
    Meetup
    Melvinisms
    Metaprogramming
    Mobile
    Ruby
    Stockpile
    Training

© COPYRIGHT 2018. ALL RIGHTS RESERVED.
  • HOME
  • About Me