Sunday, October 7, 2012

Selenium - Click and tell me what page I landed on

In this example I show you how to, using Perl and Selenium, write a reusable function that will click on a given element and report back the page it landed on. This is useful when checking menus as well as process flows. For example at each step of a registration or an order process. First the code:
1:  sub click_and_verify {  
2:    
3:    my $self = shift;  
4:    my $element_type = shift;  
5:    my $name = shift;  
6:    
7:    my $query = "SELECT element_name, locator  
8:           FROM html_element_tbl  
9:           WHERE element_type = '$element_type'  
10:           AND name = '$name'  
11:           AND is_active = true;";  
12:    
13:    
14:    my $dbh = Custom::WepaSubs::db_get_handle();  
15:    
16:    my @elem = $dbh->selectrow_array($query);  
17:    
18:    my ($target, $locator) = ($elem[0], $elem[1]);  
19:      
20:    $self->{driver}->find_element($target, $locator)->click() and Custom::WepaSubs::wait_for(1.5);  
21:    my $landing_page = $self->{driver}->get_current_url();  
22:    return $landing_page;  
23:      
24:  }  
Then from your test script you call this function and pass to it the element type and name of the object on the page you want to click on:
 my $landing_page = $web_app->click_and_verify('menu_item', 'send_mail');  
click_and_verify returns the URL of the page we landed on after the click action occurred. You can then use this URL ($landing_page) to compare to the Expected Result criteria URL ($ref_page):
1:  if ($landing_page eq $ref_page) {  
2:    # we didn't navigate so fail  
3:    unlike ($landing_page, qr/$ref_page/, 'Clicked on ' . $menu_item . ' and landed on ' . $landing_page);  
4:    $web_app->get_screenshot('ERROR', 'ReqID_0380_sendmail_dbsetup_access_' . 'menu_' . $menu_item . '_');  
5:  }  
6:  else {  
7:    cmp_ok ($landing_page, '=~', APPHOME, 'Clicked on ' . $menu_item . ' and landed on ' . $landing_page);  
8:    $web_app->get_screenshot('NORMAL', 'ReqID_0380_sendmail_dbsetup_access_' . 'menu_' . $menu_item . '_');  
9:  }  
If you're wondering about the cmp_ok and unlike methods I urge you to check out Test::More on CPAN (you'd be glad you did).

That's it. Just another tool to add to your testing arsenal. Any clarifications just ask (the code above is extracted from working code). I use page objects to model the web sites and web applications I develop test suites for. As well Selenium commands are abstracted. This is why you see references to $self and $web_app in the sample code.
Creative Commons License
VGP-Miami Web and Mobile Automation Blog by Alfred Vega is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.