測(cè)試成功,沒有看到任何Watir的影子。
(三)單獨(dú)使用Watir
	    聽說有非常fashionable的office lady用Watir來完成日常例行并且繁瑣的網(wǎng)頁點(diǎn)擊工作的(當(dāng)然不是測(cè)試),聽說而已,但是Watir的確可以完成諸如此類的網(wǎng)頁模擬操作,接下類我們用Watir來完成google搜索功能,新建watir_google.rb文件并加入以下內(nèi)容:
	復(fù)制代碼
	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
復(fù)制代碼
當(dāng)執(zhí)行到第2行時(shí),一個(gè)瀏覽器窗口會(huì)自動(dòng)打開,之后訪問google主頁(第3行),設(shè)置搜索關(guān)鍵詞"ThoughtWorks",后點(diǎn)擊搜索按鈕,單獨(dú)運(yùn)行Watir成功,沒有任何Cucumber的影子。
(四)用Cucumber+Watir寫自動(dòng)化測(cè)試
	    由上文可知,Cucumber只是用接近自然語言的方式來描述業(yè)務(wù)行為,而Watir則只是對(duì)人為操作網(wǎng)頁的模擬。當(dāng)使用Cucumber+Watir實(shí)現(xiàn)自動(dòng)化測(cè)試時(shí),通過正則表達(dá)式匹配將Cucumber的行為描述與Watir的網(wǎng)頁操作步驟耦合起來即可。同樣以Google搜索為例,搜索關(guān)鍵字后,我們希望獲得搜索結(jié)果,先用Cucumber完成搜索行為描述:
	復(fù)制代碼
	1Feature:Googlesearch
	2Scenario: search for keyword
	3Given I amongoogle home page
	4WhenI searchfor'ThoughtWorks'
	5ThenI should be able toviewthe search result of 'ThoughtWorks'
復(fù)制代碼
	   對(duì)應(yīng)的Watir代碼如下:
	復(fù)制代碼
	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
復(fù)制代碼
運(yùn)行cucumber,一個(gè)新的瀏覽器被打開,顯示結(jié)果與(三)中相同。
(五)自動(dòng)化測(cè)試的設(shè)計(jì)模式:Page對(duì)象
	   在上面的例子中,我們?cè)谒械膕tep中均直接對(duì)@browser對(duì)象進(jìn)行操作,對(duì)于這樣簡(jiǎn)單的例子并無不妥,但是對(duì)于動(dòng)則幾十個(gè)甚至上百個(gè)頁面的網(wǎng)站來說便顯得過于混亂,既然要面向?qū)ο螅覀兿M麑⒉煌捻撁嬉灿脤?duì)象來封裝,于是引入Page對(duì)象,既可完成對(duì)頁面的邏輯封裝,又實(shí)現(xiàn)了分層重用。此時(shí)位于high-level的Cucumber文件無需變動(dòng),我們只需要定義一個(gè)Page對(duì)象來封裝Google頁面(google-page.rb):
	復(fù)制代碼
	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