In any PageObject page (class), you can define a method that handles cookies, and access it using PageObject. There are several ways to implement PageObject, depending on what other frameworks you may be using, but here's an example using IRB.
# Using watir-webdriver
class MyPage
include PageObject
def delete_cookies
# Just wrapping this so it's convenient in my PageObject
@browser.cookies.clear
end
def get_cookies_as_array
# Returns an array of hashes for each cookie
@browser.cookies.to_a
end
def set_browser_cookies( cookie_hash )
# Store the cookie name and value
@browser.cookies.add( cookie_hash[:name], cookie_hash[:value] )
end
def restore_browser_cookies( cookie_array )
cookie_array.each do | cookie_hash_from_array |
self.set_browser_cookies( cookie_hash_from_array )
end
end
end
IRB Example:
>> require "watir-webdriver"
>> require "page-object"
>> @browser = Watir::Browser.start "http://stackoverflow.com"
>> my_page = MyPage.new(@browser)
>> @cookies_to_keep = my_page.get_cookies_as_array
# Observe the cookies look like this:
# [0]
# ...
# [5] {
# :name => "gauthed",
# :value => "1",
# :path => "/",
# :domain => "stackoverflow.com",
# :expires => nil,
# :secure => false
# }
#
>> my_page.delete_cookies
"" # Empty string is returned
>> my_page.get_cookies_as_array
[] # Empty Array returned because there are no cookies
>> my_page.restore_browser_cookies( @cookies_to_keep )
# Cookie array is returned
The original cookies are restored with their original :name and :value.
The API Docs that Justin Ko pointed you to are a very valuable reference.