測試成功,沒有看到任何Watir的影子。
(三)單獨使用Watir
聽說有非常fashionable的office lady用Watir來完成日常例行并且繁瑣的網(wǎng)頁點擊工作的(當然不是測試),聽說而已,但是Watir的確可以完成諸如此類的網(wǎng)頁模擬操作,接下類我們用Watir來完成google搜索功能,新建watir_google.rb文件并加入以下內(nèi)容:
復制代碼
1require 'watir-webdriver'
2browser = Watir::Browser.new :chrome
3browser.goto"www.google.com/"
4browser.text_field(:name=> "q").set"ThoughtWorks"
5browser.button(:name=> "btnG").click
復制代碼
當執(zhí)行到第2行時,一個瀏覽器窗口會自動打開,之后訪問google主頁(第3行),設置搜索關鍵詞"ThoughtWorks",后點擊搜索按鈕,單獨運行Watir成功,沒有任何Cucumber的影子。
(四)用Cucumber+Watir寫自動化測試
由上文可知,Cucumber只是用接近自然語言的方式來描述業(yè)務行為,而Watir則只是對人為操作網(wǎng)頁的模擬。當使用Cucumber+Watir實現(xiàn)自動化測試時,通過正則表達式匹配將Cucumber的行為描述與Watir的網(wǎng)頁操作步驟耦合起來即可。同樣以Google搜索為例,搜索關鍵字后,我們希望獲得搜索結果,先用Cucumber完成搜索行為描述:
復制代碼
1Feature:Googlesearch
2Scenario: search for keyword
3Given I amongoogle home page
4WhenI searchfor'ThoughtWorks'
5ThenI should be able toviewthe search result of 'ThoughtWorks'
復制代碼
對應的Watir代碼如下:
復制代碼
1require "rubygems"
2require "watir-webdriver"
3require 'rspec'
4Given /^I amongoogle home page$/do
5@browser = Watir::Browser.new :chrome
6@browser.goto("www.google.com")
7end
8
9When/^I searchfor'([^"]*)'$/ do |search_text|
10@browser.text_field(:name => "q").set(search_text)
11@browser.button(:name => "btnK").click
12end
13
14Then /^I should be able to view the search result of '([^"]*)'$/do|result_text|
15@browser.text.should include(result_text)
16end
復制代碼
運行cucumber,一個新的瀏覽器被打開,顯示結果與(三)中相同。
(五)自動化測試的設計模式:Page對象
在上面的例子中,我們在所有的step中均直接對@browser對象進行操作,對于這樣簡單的例子并無不妥,但是對于動則幾十個甚至上百個頁面的網(wǎng)站來說便顯得過于混亂,既然要面向對象,我們希望將不同的頁面也用對象來封裝,于是引入Page對象,既可完成對頁面的邏輯封裝,又實現(xiàn)了分層重用。此時位于high-level的Cucumber文件無需變動,我們只需要定義一個Page對象來封裝Google頁面(google-page.rb):
復制代碼
1require "rubygems"
2require "watir-webdriver"
3require "rspec"
4
5class GooglePage
6def initialize
7@browser = Watir::Browser.new :chrome
8@browser.goto("www.google.com")
9end
10
11def search str
12@browser.text_field(:name=> "q").set(str)
13@browser.button(:name=> "btnK").click
14end
15
16def has_text text
17@browser.text.should include(text)
18end
19end