Unable to use OptionParser and rspec

和自甴很熟 提交于 2021-01-28 05:08:13

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7077026/unable-to-use-optionparser-and-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!