Željko Filipin's blog.
Home Blog Tags Now License

View on GitHub
7 February 2006

Watir, Ruby, Objects and Variables

by Željko Filipin

I test web applications for living. I use Ruby and Watir for automating functional tests. My scripts have grown, so I made a little framework to make them simpler (all code in this post is simplified and not tested).

Class Page makes checking page URL and text(s) easier.

class Page
  def initialize(ie, url, texts)
    @ie, @url, @texts = ie, url, texts
  def check
    @texts.each do |text|
    assert_equal(@url, @ie.url)

View item page at application under test has text (breadcrumb) {item_type} > View (example: File > View).

After item is added/edited, at that page there is also text {item_type} {action} (example: File added.).

Class File tests files, of course.

class File
  def initialize
    @page_view =
        ["File > View"])
    @page_view_after_add =
        ["File > View", "File added."])
    @page_view_after_edit =
        ["File > View", "File edited."])
  def add
    # add file
  def edit
    # edit file
  def view
    # go to file

And it works just nice. All I have to write is this.

file =

There are three objects. One for each (@page_view...) variable. id in Page:{id} is different for each variable.

#<Page:0x2b5ac28 @url="", @texts=["File > View"]>
#<Page:0x2b5ab98 @url="", @texts=["File > View", "File added."]>
#<Page:0x2b5ab08 @url="", @texts=["File > View", "File edited."]>

But, duplication bugs me.

I would like that File#initialize looks like this.

@page_view = @page_view_after_add = @page_view_after_edit =
  ["File > View"])
@page_view_after_add.texts < < "File added."
@page_view_after_edit.texts << "File edited."

But (surprise!), it does not work. Well, I am pretty new in object oriented world, so this was not really a surprise for me.

This way only one Page object is created, and all three variables point to it. No matter which variable I change, it changes the object it points to. Result is that all three variables are the same. Not what I wanted to do.

#<Page:0x2820048 @url="", @texts=["File > View", "File added.", "File edited."]>
#<Page:0x2820048 @url="", @texts=["File > View", "File added.", "File edited."]>
#<Page:0x2820048 @url="", @texts=["File > View", "File added.", "File edited."]>

I have tried a few alternatives, but none worked. I will live with duplication for now, but I would like to remove it from my scripts.

tags: code - ruby