您可以通过创建具有 before 和 after all 测试方法的自定义测试运行器类型来做您想做的事情。然后,您可以在所有测试之前创建一个 selenium-webdriver 实例,并在所有测试之后关闭它。
这是在所有测试之前启动浏览器并转到 Google 的示例。然后每个测试重复使用相同的浏览器。
require 'minitest/autorun'
require 'selenium-webdriver'
#Add before and after suite hooks using a custom runner
class MyMiniTest
class Unit < MiniTest::Unit
def _run_suite(suite, type)
begin
suite.before_suite if suite.respond_to?(:before_suite)
super(suite, type)
ensure
suite.after_suite if suite.respond_to?(:after_suite)
end
end
end
end
MiniTest::Unit.runner = MyMiniTest::Unit.new
class GoogleTest < MiniTest::Unit::TestCase
def self.before_suite
p "before all tests"
@@driver = Selenium::WebDriver.for :firefox
@@driver.navigate.to 'http://www.google.com'
end
def self.after_suite
p "after all tests"
@@driver.quit
end
def setup
p 'setup before each test'
end
def teardown
p 'teardown after each test'
end
def test1
p 'test1'
assert_equal(0, @@driver.find_elements(:xpath, '//div').length)
end
def test2
p 'test2'
assert_equal(0, @@driver.find_elements(:xpath, '//a').length)
end
end
您可以看到输出运行的顺序:
"before all tests"
"setup before each test"
"test1"
"teardown after each test"
"setup before each test"
"test2"
"teardown after each test"
"after all tests"
请注意,您要跨测试共享的变量需要是类变量(即以@@ 为前缀)。