2

我试图通过只打开和关闭浏览器一次来提高运行测试的速度。

http://watirmelon.com/2012/04/01/five-page-object-anti-patterns/

我在 hooks.rb 中有以下内容

browser = Watir::Browser.new ENV['BROWSER'].to_sym

Before do
  @browser = browser
end

After do |scenario|
  @browser.cookies.clear
end

at_exit do
  browser.close
end

它极大地提高了测试套件的运行速度。但是我还需要来自我的自定义格式化程序的 json 文件中的一些统计信息,而无需运行测试:

cucumber -t @test -d -f Cucumber::Formatter::MyCustomFormatter > result.json

问题是黄瓜使用-d选项捕获错误:

uninitialized constant Watir (NameError)
/home/user/work/repository/features/support/hooks.rb:7:in `<top (required)>'
/home/user/.rvm/gems/ruby-2.0.0-p247/gems/cucumber-1.3.5/lib/cucumber/rb_support/rb_language.rb:122:in `load'
/home/user/.rvm/gems/ruby-2.0.0-p247/gems/cucumber-1.3.5/lib/cucumber/rb_support/rb_language.rb:122:in `load_code_file'
/home/user/.rvm/gems/ruby-2.0.0-p247/gems/cucumber-1.3.5/lib/cucumber/runtime/support_code.rb:180:in `load_file'
/home/user/.rvm/gems/ruby-2.0.0-p247/gems/cucumber-1.3.5/lib/cucumber/runtime/support_code.rb:83:in `block in load_files!'
/home/user/.rvm/gems/ruby-2.0.0-p247/gems/cucumber-1.3.5/lib/cucumber/runtime/support_code.rb:82:in `each'
/home/user/.rvm/gems/ruby-2.0.0-p247/gems/cucumber-1.3.5/lib/cucumber/runtime/support_code.rb:82:in `load_files!'
/home/user/.rvm/gems/ruby-2.0.0-p247/gems/cucumber-1.3.5/lib/cucumber/runtime.rb:183:in `load_step_definitions'
/home/user/.rvm/gems/ruby-2.0.0-p247/gems/cucumber-1.3.5/lib/cucumber/runtime.rb:42:in `run!'
/home/user/.rvm/gems/ruby-2.0.0-p247/gems/cucumber-1.3.5/lib/cucumber/cli/main.rb:47:in `execute!'
/home/user/.rvm/gems/ruby-2.0.0-p247/gems/cucumber-1.3.5/bin/cucumber:13:in `<top (required)>'
/home/user/.rvm/gems/ruby-2.0.0-p247/bin/cucumber:23:in `load'
/home/user/.rvm/gems/ruby-2.0.0-p247/bin/cucumber:23:in `<main>'
/home/user/.rvm/gems/ruby-2.0.0-p247/bin/ruby_noexec_wrapper:14:in `eval'
/home/user/.rvm/gems/ruby-2.0.0-p247/bin/ruby_noexec_wrapper:14:in `<main>'

然后我尝试在块Watir.new内移动方法Before

Before do
  if !$somevar
    browser = Watir::Browser.new ENV['BROWSER'].to_sym
    @browser = browser
    $somevar = true
  end
end

at_exit并在块中出错:

/home/user/work/repository/features/support/hooks.rb:26:in `block in <top (required)>': undefined local variable or method `browser' for main:Object (NameError)

如果我把@browser.close里面at_exit,我得到:

/home/user/work/repository/features/support/hooks.rb:26:in `block in <top (required)>': undefined method `close' for nil:NilClass (NoMethodError)

有没有办法在测试套件中打开/关闭浏览器并使其与-d黄瓜选项一起使用?

4

1 回答 1

2

问题是空运行 (-d) 不会加载您的 support/env.rb 文件。如果您确实cucumber -h看到了帮助,它会说:

-d, --dry-run 调用格式化程序而不执行这些步骤。如果存在,这也会省略加载您的 support/env.rb 文件。

由于您在 env.rb 中需要 watir-webdriver 并且 env.rb 没有被加载,因此您的 hooks 文件将不知道 Watir 是什么。

一种解决方案是将require 'watir-webdriver'(或require 'watir')添加到您的 hooks.rb 文件中。

另一种解决方案是将浏览器创建和 at_exit 挂钩移动到 env.rb 文件中。这样,在使用空运行选项时,您将看不到浏览器打开和关闭。

于 2013-08-28T12:53:46.647 回答