Ruby中的Webdriver,如何通过创建类来使可重复使用

时间:2013-10-07 04:18:28

标签: ruby webdriver selenium-webdriver

我在下面的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脚本。

LogIn.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

HelloWorld.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中实例化驱动程序,我以后就无法访问它的属性。

你管理这种情况的方式是什么?

感谢您的帮助。

提前致谢。

1 个答案:

答案 0 :(得分:1)

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

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

<强> HelloWorld.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

<强> Login.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