在Rails底下寫程式很容易不知不覺把時間花在測試上頭。
第一個原因是因為以Agile方式進行時,會先寫測試程式,再寫程式;只要通過測試程式這關,程式就差不多寫好了;在這種方式之下,測試程式很像是實際程式的導航系統,先把路線定好,照著走就對了。
第二個原因是Ruby/Rails的程式真的很好寫,很快就可以寫完一個功能,在沒事可做的情況下,就會想去加強測試項目,讓程式更加嚴謹。
下面是一個簡單的網路書店測試程式。大致上的意思是說,有兩個網路書店員工在那裡搗亂,一個新增資料,另一個刪除:
def test_for_bookstore
winson = new_user(:winson) # Open new session.
steven = new_user(:steven) # Open 2nd session.
drmaster = winson.add_publisher('Dr Master')
loney = steven.add_author('Loney','Koch')
mybook = steven.add_book :book => {
:title => 'UML On Rails',
# Blahblah...
}
steven.list_books
winson.show_book mybook
winson.edit_book mybook, :book => {
:title => 'SQL On Rails',
# Blahblah...
}
steven.show_book mybook
steven.delete_book mybook
end要強調的是,這裡所作的檢查,並不只是檢查資料庫有沒有資料而已,也檢查到網頁上有沒有帶入這個資料,或相關選項,例如add_book:def add_book(params)
author = Author.find(:all).first
publisher = Publisher.find(:all).first
get '/store/admin/book/new'
assert_response :success
assert_template 'admin/book/new'
assert_tag :tag => 'option', :attributes => {:value => publisher.id}
assert_tag :tag => 'select', :attributes => {:id => 'book[author_ids][]'}
post '/store/admin/book/create', params
# Blahblah...
end像add_book這樣把一連串檢查動作簡化成一句簡單的白話英文,這就是DSL。換句話說,連白癡都看得懂那兩名員工在搞什麼鬼。
Ruby/Rails在測試這塊真的可以說是輕鬆愉快,像其他平台、語言或許覺得Selenium很好用,因為搭配Firefox外掛之後,可以輔助輸入或錄製測試腳本,但我試著用Selenium On Rails之後,只覺得他的語法不會比Ruby/Rails簡單到哪去,又因為Ruby/Rails語法簡單,所以也不需要用Firefox外掛來作輔助輸入了。
反倒是Ruby/Rails的物件導向及簡便的天性,可以造就出令人激賞的DSL。
而Watir On Rails Plugin則是另一個相當有前景的測試工具,他可以直接寫腳本開啟瀏覽器,把測試動作”跑給你看”,他跑的當然不是Selenium那種畫面,而是在瀏覽器上對著實際的系統輸入測試資料,例如以下語法:
def test_new_author
browser = open_browser
browser.goto("http://demo.org/admin/author/new")
browser.text_field(:name, "author[first_name]").set("Hi")
browser.text_field(:name, "author[last_name]").set("there")
browser.button(:name, "Create").click
browser.close
end這不但語法簡單,而且大家都看得懂,這東西跑起來,可能連客戶都笑呵呵吧。
Ruby/Rails的領域隨處都在貫徹”快樂寫程式”的哲學,連測試都毫不例外。
