1

I have a simple watir (web-driver) script which goes to google. But, I want to use option parser to set an argument in the cmd to select a browser. Below is my script:

require 'optparse'
require 'commandline/optionparser'
include CommandLine
require 'watir-webdriver'

describe 'Test google website' do

  before :all do

    options = {}

    opts = OptionParser.new do |opts|

      opts.on("--browser N",
        "Browser to execute test scripts") do |n|
        options[:browser] = n
        $b = n.to_s
      end
    end

    opts.parse! ARGV

    p options
  end

  describe 'The test website should be displayed' do

    it 'should go to google' do
      $ie = Watir::Browser.new($b)
      #go to test website
  $ie.goto("www.google.com")
    end
  end
end

Executing rspec ietest.rb --browser firefox -f doc just gives me invalid option, ietest is the name of my file. Any other intuitive ways of setting a browser through web driver, with out changing script code, would be welcome.

Serabe
  • 3,834
  • 19
  • 24
Sun
  • 2,658
  • 6
  • 28
  • 33

2 Answers2

8

You cannot use rspec with OptionParser since the rspec executable itself parses its own options. You cannot "piggy back" your options on the rspec options.

If you must do something like this then use either a settings file (spec_config.yml or similar), or use an environment variable:

BROWSER=firefox spec test_something.rb

And then in your code you can use ENV['BROWSER'] to retrieve the setting.

Casper
  • 33,403
  • 4
  • 84
  • 79
1

Please, learn about RSpec because I am guessing you have no clue about it (just google it). There are no expectations and you are writing your functionality in it.

require 'optparse'
require 'commandline/optionparser'
include CommandLine
require 'watir-webdriver'

options = {}

opts = OptionParser.new do |opts|

opts.on("--browser N",
  "Browser to execute test scripts") do |n|
  options[:browser] = n
end

opts.parse! ARGV

p options

ie = Watir::Browser.new(options[:browser].to_s)
#go to test website
ie.goto("www.google.com")

That should work.

EDIT: If you want to test it do something like this:

def open_url_with_browser(url, browser = 'firefox')
  nav = Watir::Browser.new(browser)
  nav.goto(url)
end

Then you would test that method in a spec. Just stub new, and goto in different specs.

If you are still wondering why are you getting the invalid option is because you are passing --browser to rspec, not your script, as intended.

Serabe
  • 3,834
  • 19
  • 24
  • I know the code worked before but I wanted it to work with rspec, I know the rspec code that I wrote is bad but it was a simple test to see how I can use rspec and OptionParser. Thanks for the help though. – Sun Aug 16 '11 at 11:49
  • Thanks again for the help, it looks like I'll use something like this then. – Sun Aug 16 '11 at 12:36