Watir - การทำงานกับเบราว์เซอร์
โดยค่าเริ่มต้น Watir จะเปิดเบราว์เซอร์ Chrome ในกรณีที่ไม่ได้ระบุชื่อเบราว์เซอร์ มีการติดตั้งไดรเวอร์เบราว์เซอร์ที่จำเป็นพร้อมกับการติดตั้ง Watir ในกรณีที่คุณประสบปัญหาใด ๆ ในการทำงานกับเบราว์เซอร์ให้ติดตั้งไดรเวอร์ตามที่แสดงในบทไดรเวอร์ของเบราว์เซอร์และอัปเดตตำแหน่งในตัวแปร PATH
ในบทนี้เราจะเข้าใจวิธีการเปิดเบราว์เซอร์โดยใช้ Watir
ขั้นตอนในการเปิดเบราว์เซอร์โดยใช้ Watir
เปิด IDE RubyMine และสร้างไฟล์ใหม่: test1.rb


เลือกตกลงและคลิกรูปแบบไฟล์เป็นทับทิมดังที่แสดงด้านล่าง -

คลิกตกลงเพื่อสร้างไฟล์
ตอนนี้เราจะเขียนโค้ดง่ายๆที่จะเปิดเบราว์เซอร์ดังที่แสดงด้านล่าง -
test1.rb
require 'watir'
Watir::Browser.new

คลิกที่ปุ่ม Run ที่ไฮไลต์ใน IDE ดังที่แสดงด้านบน เมื่อคลิกที่ Run มันจะเปิดเบราว์เซอร์ดังที่แสดงด้านล่าง -

เบราว์เซอร์จะเปิดและปิดโดยอัตโนมัติ ให้เราเพิ่มรหัสเพิ่มเติมใน test1.rb
เราสามารถระบุชื่อของบราวเซอร์ได้ดังรูปด้านล่าง -
ตัวอย่างสำหรับ Chrome
require 'watir'
Watir::Browser.new :chrome
ตอนนี้ให้เราเปิด page-url ในกรณีทดสอบของเรา
ตัวอย่าง
require 'watir'
browser = Watir::Browser.new
browser.goto("https://www.google.com")
คลิกที่ Run เพื่อดูผลลัพธ์ที่แสดงด้านล่าง -

ในทำนองเดียวกันคุณสามารถเปิดเบราว์เซอร์ firefox, safari, Internet explorer
ตัวอย่างสำหรับ Firefox
require 'watir'
Watir::Browser.new :firefox

ตัวอย่างสำหรับ Internet Explorer
Watir Code
require 'watir'
browser = Watir::Browser.new :ie
browser.goto("https://www.google.com")
เมื่อเรารันโค้ดข้อผิดพลาดต่อไปนี้จะปรากฏขึ้น -
Unable to find IEDriverServer. Please download the server from
(Selenium::WebDriver::Error::WebDriverError)
http://selenium-release.storage.googleapis.com/index.html and place it
somewhere on your PATH.
More info at
https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver.
ซึ่งหมายความว่าแพ็คเกจ watir ไม่มีไดรเวอร์ InternetExplorer เราได้ดาวน์โหลดสิ่งเดียวกันจากที่นี่ -https://docs.seleniumhq.org/download/ และอัปเดตในตัวแปร PATH
ตอนนี้เรียกใช้อีกครั้งเพื่อดูเบราว์เซอร์ Internet Explorer ที่เปิดขึ้นตามที่แสดงด้านล่าง -

รหัส Watir เพื่อเปิด Safari Browser
require 'watir'
browser = Watir::Browser.new :safari
browser.goto("https://www.google.com")
รหัส Watir ไปยังเบราว์เซอร์ Microsoft Edge
require 'watir'
browser = Watir::Browser.new :edge
browser.goto("https://www.google.com")