include Watir

Don't put "include Watir" at toplevel

A common practice has been for Watir users to put

require 'watir'
include Watir

at the top of their scripts. The require statement is fine, but the include statement is a bad practice and can lead to trouble. And with Watir 1.6, it will fail your script ("no such file to load – safariwatir").

Why "include Watir" is trouble

The include statement, says "take everything in the Watir module and add it all to the current object." This is fine if you are in the context of a class, but at the top of a file, you are in the context of the God object, and therefore will affect every class, object and module in ruby.

Don't believe us? Here's proof.

>> module Watir; def abuse_ruby; 'ouch!'; end; end
=> nil
>> include Watir
=> Object
>> 7.abuse_ruby
=> "ouch!"
>> "wtf?".abuse_ruby
=> "ouch!"
>> Integer.abuse_ruby
=> "ouch!"

First we added a method (abuse_ruby) to the Watir module. Then we included this module at toplevel. Now we see that every object in Ruby now has our new method – every number, string, class – everything.

Many people try to avoid using global variables. Why? Because their affect is global, and this means there is the risk that some other module somewhere might be using the same variable leading to a conflict. Using include at toplevel has much more wide-ranging implications and is much more likely to lead to trouble than using global variables.

But it was working for me before Watir 1.6

You were lucky. The reason this no longer works is complicated. In short, there is a conflict with the activesupport library, which is now being used by Watir to simplify the code base.

How should I fix my scripts?

There are two options.

  1. Don't use include at all. Instead make reference directly to Watir::IE or Watir::Browser.
  2. Move the include statement to the class where it is being used. There is nothing improper about using the include statement in the context of a class, like your test case class. This is what it is for. This is the best option if you are using the wait_until method.

But I was just following the example

Sorry.

Watir example code used to have include Watir at toplevel. This is why many people use it today. We have been fixing our examples. If you see example code that has include Watir at toplevel, please fix it or let us know about it. Thanks.

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.