Processing defaults in watir elements

Looking at watir code there is a nice patterns for accepting defaults for ‘how’ in method names for elements. Currently for frame, form and button.

like this:

I like this solution for my test framework. I have been thinking of making a small change to my snagit screenshot.
Basically be default I want it to take a screenshot of a :desktop but I also want it to snag a webpage with scrolling.
I still need to understand why the how.class is compared to String and not to Symbol.

And on another note I need to start watir.testr.us page for all watir related info in one place. - The Place To Put Things is a constant challenge, it seems.

Desktop Screenshots with Watir, win32screenshot, RMagick and Snagit

Here is what I had with win32screenshot and RMagick (later replaced with Snagit)

# Runtime Test Housekeeping place
module TestRun

  # at runtime takes a screenshot of the desktop and saves it in log dir.
  # you must install win32screenshot gem and RMagic package for this to work.
  def self.screenshot(context=nil)
    if $testrun[:screenshot] == true
      # prevent runtime error when screenshot gem and RMagic are not installed on client machine.
      begin
        require ‘win32screenshot’
        require ‘RMagick’
        width, height, bitmap = Win32::Screenshot.desktop
        imglist = Magick::ImageList.new
        imgl = imglist.from_blob(bitmap)
        time_stamp_s = Time.new.strftime(’%m%d_%H%M_%S’)
        screenshot_filename = context ? “#{time_stamp_s}_#{context}.png” : “#{time_stamp_s}.png”
        imgl.write(File.join(logpath,screenshot_filename))
        $log.info(”Screenshot captured: #{screenshot_filename}”)
      rescue Exception => ex
        $log.error(”TestRun.screenshot(#{context} — #{ex}”)
      end

    end

  end

end

#usage
TestRun.screenshot() # => makes a MMDD_HHMM_SS.png file
TestRun.screenshot(’blabla’) # appends the string to filename.

The above is an older solution, I’ve had it working for a while but now it has stopped after I upgraded rubygems system. It still works on my other test machines but not on my primary box.

Instead I have installed snagit 8 and I am using it for web page capture. it’s better, definitely better with the COM interface.
I just wanted to post the code here in case I need to refer to it again in the future. (note: logpath method returns path to log directory. The global $testrun hash holds runtime options for the test framework.

Thanks win32screenshot and thanks RMagick, it was fun using it, moving on to snagit OLE interface.

UPDATE:
Here is my current reimplementation using snagit

def self.screenshot(context=nil)
    if $testrun[:screenshot] == true #runtime options guard access

      begin
        require ‘win32ole’
        snagit = WIN32OLE.new(’Snagit.ImageCapture’)
        time_stamp_s = Time.new.strftime(’%m%d_%H%M_%S’)
        screenshot_filename = context ? “#{time_stamp_s}_#{context}” : “#{time_stamp_s}”
        # config input
        snagit.Input = 0 #desktop
        #configure output
        snagit.Output = 2 #file
        snagit.OutputImageFile2.FileType = 5 #:png
        snagit.OutputImageFile2.FileNamingMethod = 1 # fixed #
        #location
        snagit.OutputImageFile2.Directory = logpath   # set directy where filename will be saved
        snagit.OutputImageFile2.Filename = screenshot_filename
        # do the duty
        snagit.Capture
        # wait for capture to complete
        until snagit.IsCaptureDone do
          sleep 0.5
        end
        $log.info(”Screenshot captured: #{screenshot_filename}”)
      rescue Exception => ex
        $log.error(”TestRun.screenshot(#{context} — #{ex}”)
      end
    end
  end

The above works pretty well. my next thing is to implement taking a screenshot of a page with setting Input active window and scrolling it. It’ll be fun.

Doing the Web Test in 3 acts with Watir

In a Story or UseCase for Web Application you can decompose a test into 3 acts. or Steps. (Actually I don’t like to speak of Preconditions and Steps. I much rather speak of Context and Acts in a Web Application testing).

class ThreeStepTest
  attr_accessor :context

  # config context for the test
  def initizlie(context)
     @context = context
  end

  # act one
  def set_request
    # given context configure the page with data.
    # Delegate to watir implementer here to send data to the page.
  end

  # act two
  def submit_request
    # delegate to watir to click on a page to submit form or request next page
  end

  # act three
  def verify_response
    # get context
    @context =
  end
end

class Context
  attr_accessor :given, :expected, :actual

end

the set_request occurs in a Given Context which was created by the previous verify_response.

So a test scenario can be constructed a series of those 3 acts. Context has a :given as a precondition to start with, :expected and :actual.

Anyway, this is just some thinking about constructing Watir framework

Towards MVC framework for Watir Tests

I was thinking about what I call FUNTOM but more and more I call it Semantic Test Objects. Here is my example unofolding towards an MVC type framework for using Watir as my view through some adapters.

#example of class as Semantic Test Object which has mixing of module providing behaviour.
# This sould be a strategy pattern type thinking but who knows.
# it's just my investigations into watir implementation
module DefaultBehavior
  def wag
    puts 'default wag left to right'
    # here call Watir Adapters to delegate actions to the webpage
  end
  def bark
    puts 'woof woof default bark'
  end
end

module SpecialBehavior
  include DefaultBehavior
  def bark
    puts 'raah raah special bark'
  end
end

class DogAsTestModel
  include DefaultBehavior
end

DogAsTestModel.new.wag
DogAsTestModel.new.bark

class DogAsTestModel
  include SpecialBehavior
end

DogAsTestModel.new.wag
DogAsTestModel.new.bark

class DogAsTestModel
  include SpecialBehavior
  def bark
    puts 'overwrite bark. Woooooof Woooooof'
  end
end

DogAsTestModel.new.wag
DogAsTestModel.new.bark

The idea is that class represents Semantic Test Object. It could be a collection of objects on a page.
more to come I hope.

Using HttpWatch with Watir

HttpWatch is a great add-on tool to Internet Explorer that captures your IE HTTP traffic. The best part for me is that it can be driven programaticly from my Watir Tests. The company Simtec has an example of how to do it on their website. So I would recommend you install HttpWatch and run the example for yourself first or just follow along for some other way of looking at the tool.

The complete API documentation is available as a chm file you get with installation, I hope they’ll put it as html online rather than chm so you can google it and link to it.

Here are some of my notes when I investigated the tool for my projects. - It works for me out of the box. (I also use Fiddler2, another great HTTP sniffer). HttpWatch fills my immediate need for Http traffic data which IE natively does not provide and a nice color coding logger makes for a sugar candy for managment and testers alike.

For some of you in the dark about how to use it (I was in the dark when I first encountered the tool) here are some notes and how I understand the usage of the tool so far. (check out the mindmap too. I will update soon.)

So let’s begin investigation. it’s best to run everything from IRB (or just jump to watir-console, see
C:\ruby\lib\ruby\gems\1.8\gems\watir-1.5.3\bin\watir-console)

Open IRB and type some infrastructure code:

require 'watir' # watir requires 'win32ole'
ct = WIN32OLE.new('HttpWatch.Controller')
ie = Watir::IE.new
httpw = ct.Attach(ie.ie)

We just created Controller, then IE instance and made a plugin object httpw by attaching our ie.ie object. In Watir IE class maintains an OLE ie object. This is the object use and not the actual IE from Watir, that’s why to confuse you further we used the same name ie for our main IE object.
Now that you may be confused enough we’ll just plunge in more to see what else we can do.

So far I got a blank IE sitting on the desktop (I am using WinXP and IE6x) and an IRB session open.
Let’s start the Recorder (after clearing the Log)

httpw.Clear
httpw.Record

# generate traffic with watir
ie.goto('http://google.com/')
ie.goto('http://yahoo.com/')
ie.goto('http://blablablaichbinnichtda.com')
ie.goto('http://marekj.com/iwasneverhier.html')

For traffic I just visited two sites I know exist and two pages that do not exist to Log errors.
Now you can stop the recording and save your logs (in case you close IE or crash)

httpw.Stop
httpw.Log.Save('temp.hwl')

Let’s do some fact finding about the http sessions.

#How long did all of this take?
httpw.Log.Entries.Summary.Time

Careful: this is the Time it took from the start to the end of the session including all the waiting around and staring at the page, it’s not a true time in how long it took for all the traffic to arrive.

# How many pages did I visit?
httpw.Log.Pages.Count

#Were there any errors?
httpw.Log.Entries.Summary.Errors.Count

For more information just take a look at the API documentation.

The HttpWatch Basic Edition allows you to save as well as load a log file and examine the Entries. That’s very useful. I can log, stop and offload my hwl file for later review or quick audit.

Here is an example of how to create an instance of a log object by loading previously saved log file using Controller.

# load previously saves httpwatch log file
log = ct.OpenLog('temp.hwl')

NBw you can use standalone log object as if it was httpw.Log
I like this feature for gathering statistics on a previously saved test sessions.

That’s about it for the first look.(mindmap to come)