Bueno
Bueno

Reputation: 23

Error initializing driver method - undefined local variable

In my test automation project, I am using ruby with capybara, cucumber and selenium. (I already have devkit installed and chrome is starting normally)

When looking for an element in the site to select it, I am using the method driver.findElement (By.xpath (.... etc"), but when executing cucumber, it is indicating the following error:

I already removed and reinstalled the selenium-webdriver gem but it did not resolve.

Can someone help me in resolving why WebDriver does not seem to be valid in this context?

code example

(finding button logout using tag img, because the element don't have name or id)

After('@logout') do element = driver.findElement(By.xpath("//img[@src='/Portal/img/user.png']")); element.click end

Result cucumber execution

Feature: Login
Description feature

DevTools listening on ws://127.0.0.1:60121/devtools/browser/c0bacc6e-697a-4614-b82c-eb324d587df5 @logout
Scenario: Login_OK # features/support/login.feature:14
Given that i access the main portal page HRP # features/step_definitions/login_steps.rb:1
When do login using "abc123" and "abc123password" # features/step_definitions/login_steps.rb:5
Then system do login # features/step_definitions/login_steps.rb:10
And show message "Welcome to Portal." # features/step_definitions/login_steps.rb:14
undefined local variable or method `driver' for # (NameError) ./features/support/hooks.rb:4:in `After'

Failing Scenarios:
cucumber features/support/login.feature:14 # Scenario: Login_OK

1 scenario (1 failed) 4 steps (4 passed) 0m5.457s

Upvotes: 0

Views: 267

Answers (1)

Thomas Walpole
Thomas Walpole

Reputation: 49950

If you're using Capybara with Cucumber in a standard setup then you shouldn't be really ever be calling the selenium webdriver instance directly - driver (except for in some very rare circumstances). Instead you should be using the Capybara methods. What is available in your After hook depends on exactly how where you've includeed what but one of these will probably be avaialble

After('@logout') do
  element = page.find(:xpath, ".//img[@src='/Portal/img/user.png']"));
  element.click
end

or

After('@logout') do
  element = Capybara.current_session.findElement(:xpath, ".//img[@src='/Portal/img/user.png']");
  element.click
end

Note: there is probably a better way to locate the logout button than an XPath on the contained images source, but without seeing the HTML of the button it's impossible to say for sure (for instance, Capybaras button finder will match against the alt attribute of an img element nested inside a <button> element)

Upvotes: 0

Related Questions