1

我有一个简单的 watir (web-driver) 脚本,它可以访问谷歌。但是,我想使用选项解析器在 cmd 中设置一个参数来选择浏览器。下面是我的脚本:

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

执行 rspec ietest.rb --browser firefox -f doc 只是给了我无效的选项,ietest 是我的文件的名称。欢迎使用任何其他通过 Web 驱动程序设置浏览器的直观方法,而无需更改脚本代码。

4

2 回答 2

8

您不能使用 rspec with,OptionParser因为 rspec 可执行文件本身会解析自己的选项。您不能在 rspec 选项上“捎带”您的选项。

如果您必须执行类似的操作,请使用设置文件(spec_config.yml或类似文件),或使用环境变量:

BROWSER=firefox spec test_something.rb

然后在您的代码中,您可以使用它ENV['BROWSER']来检索设置。

于 2011-08-16T12:04:40.197 回答
1

请了解 RSpec,因为我猜你对此一无所知(只是谷歌它)。没有期望,您正在其中编写功能。

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")

那应该行得通。

编辑:如果你想测试它做这样的事情:

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

然后,您将在规范中测试该方法。只是 stub new,并且goto有不同的规格。

如果您仍然想知道为什么获得无效选项是因为您按预期传递--browserrspec,而不是您的脚本。

于 2011-08-16T11:42:51.377 回答