1

我在下面的 ruby​​ 中有一个简单的 webdriver 测试:

require 'rubygems'
require 'selenium-webdriver'

driver = Selenium::WebDriver.for :firefox
# example application under test
driver.get "https://dev08-olb.nz.thenational.com/ib4b/app/login"

element = driver.find_element :id => "accessId"
element.send_keys "123456"

element = driver.find_element :id => "userId"
element.send_keys "user1"

element = driver.find_element :id => "password"
element.send_keys "password1"
element.submit

if 
 "Hello".eql? driver.title
  puts "Page title is #{driver.title}"
else 
 puts "damn it, it must be Monday"
end

driver.quit

将来会有很多其他情况需要登录,所以我们希望尽可能少地重复,所以我们创建了以下两个 ruby​​ 脚本。

登录.rb

require 'rubygems'
require 'selenium-webdriver'

class LogIn
    def initialize(accessID, user, pass)
    @accessID    = accessID
    @user   = user
    @pass = pass

    driver = Selenium::WebDriver.for :firefox
    driver.get "https://dev08-olb.nz.thenational.com/ib4b/app/login"

    element = driver.find_element :id => "accessId"
    element.send_keys @accessID

    element = driver.find_element :id => "userId"
    element.send_keys @user

    element = driver.find_element :id => "password"
    element.send_keys @pass
    element.submit
  end
end

你好世界.rb

require 'rubygems'
require 'selenium-webdriver'
require './LogIn'

LogIn.new("123456","user1","password1")

driver = Selenium::WebDriver.for :firefox
 if 
 "Hello".eql? driver.title
  puts "Page title is #{driver.title}"
else 
 puts "damn it, it must be Monday"
end

driver.quit

然而,在 HelloWorld.rb 中,驱动程序被实例化了两次,因此浏览器的两个实例在测试执行时打开,这是不希望的。但是如果我不在 HelloWorld.rb 中实例化驱动程序,我以后就无法访问它的属性。

你是如何处理这种情况的?

感谢您的帮助。

提前致谢。

4

1 回答 1

1

这更多是关于如何在 Ruby 中编写测试,而不是特定于 Selenium。有很多方法可以做到这一点。

这是一个,尝试初始化driver HelloWorld.rb,然后将其传递给Login.rb

你好世界.rb

require 'rubygems'
require 'selenium-webdriver'
require './LogIn'

driver = Selenium::WebDriver.for :firefox

LogIn.new(driver, "123456","user1","password1")

 if 
 "Hello".eql? driver.title
  puts "Page title is #{driver.title}"
else 
 puts "damn it, it must be Monday"
end

driver.quit

登录.rb

require 'rubygems'
require 'selenium-webdriver'

class LogIn
    def initialize(driver, accessID, user, pass)
    @driver = driver
    @accessID    = accessID
    @user   = user
    @pass = pass

    driver.get "https://dev08-olb.nz.thenational.com/ib4b/app/login"

    element = driver.find_element :id => "accessId"
    element.send_keys @accessID

    element = driver.find_element :id => "userId"
    element.send_keys @user

    element = driver.find_element :id => "password"
    element.send_keys @pass
    element.submit
  end
end
于 2013-10-07T20:55:54.780 回答