你可以通過創建一個custom test runner type來做你想做的事情,它有一個前後測試方法。然後,您可以在所有測試之前創建一個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"
注意,你想跨越測試共享變量將需要的類變量(即@@前綴)。