Search code examples
rubyrspecwatirwatir-webdriveroptionparser

Unable to use OptionParser and rspec


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.


Solution

  • 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.