Search code examples
rubygoogle-chromewebdriverselenium-chromedriverwatir

How to put ruby-watir code into a defined method?


I wanted to write a program with ruby (watir). To keep the code clear and compact I wanted to put code into a method, which is getting called every time the code needs to be run. But calling the method throws an error and I really don't know how to solve this problem.

I tried to define/create the browser under the method (google) but that did not work either. I am a newbie to ruby and I have no idea how to fix this because the error says that the browser is undefined. If I run the code without the method, but browser.goto "google.com" instead everything works fine.

require 'watir'

browser = Watir::Browser.new :chrome

def google
  browser.goto "google.com"
end

google

I expect, that chrome is getting opened and the page "google.com" is getting navigated to. But instead I'm getting this error:

undefined local variable or method `browser' for main:Object (NameError)


Solution

  • When you write your code inside the method, it has it's scope, so pass the browser variable, it would

    require 'watir'
    
    browser = Watir::Browser.new :chrome
    
    def google browser
      browser.goto "google.com"
    end
    
    google browser