Writing less code in Watir/RSpec specs

It’s been quite awhile since i last wrote something about using Watir and RSpec, but that doesn’t mean that i’ve forgotten the topic altogether. No, i haven’t and i have a decent backlog about the topics i’m going to write.

If you look at the current specs then there are some things which seem to repeat in each spec:

  • Watir, RSpec and another libraries’ require statements
  • Opening and closing the browser in before and after :all blocks
  • include statements for helper modules
  • Accessing @browser instance variable

It is possible to get rid of all of the things mentioned above by using RSpec’s nifty features and Ruby itself!

First of all, i have an idea that all require statements should exist in specs only once - every needed library or file should be loaded into memory during start up of the specs. I think that memory is quite cheap nowadays, especially when using it for user-interface based web applications’ testing. Just load it all into your memory and don’t worry about them anymore. A file should be created for this, for example environment.rb, with all of the needed require statements. When starting specs, just load the file into memory. It is really easy to do it with RSpec. You could just execute RSpec like this:

spec -renvironment.rb spec\my_spec.rb

Or make an spec.opts file into your spec directory with the contents of:

--require
environment.rb

Now, when executing RSpec, spec.opts will be loaded automatically with all the needed libraries.

It would not make sense to require all helper files manually. I’d rather create some loop for that or use a library called require_all. Install the library with gem install require_all and use it like this in your environment.rb file:

This code makes sure that every non-spec Ruby file under spec directory will be loaded into memory. Make sure that you don’t have any Ruby files in there which you don’t want to load automatically or what would cause problems doing so. You could create another directory for this kind of files.

By loading all files automatically into memory you will avoid all of the typical require statements like this in your files:

You will also get the freedom to reorganize the file structure under spec directory without having to worry about breaking anything since you don’t have any relative or absolute paths written to anywhere!

Stay tuned for the cure for the other three nuisances mentioned above!

Update: added files related to this post to GitHub.

Update 2: added links to part II and part III.