Writing less code in Watir/RSpec specs, part III

If you’ve not read first and second part of these series already then please do so now before continuing.

In this post i’m going to demonstrate how to get rid of accessing too much @browser variable within specs. Consider the following typical RSpec example when using Watir:

In this short example @browser variable is already used four times! Think of some real example and you’ll see where this is going. @browser here, @browser there and @browser everywhere. I’m finding it to be too verbose when dealing most of the time with the browser (which is the case when writing this kind of tests anyway) and having to write @browser everywhere. Since Watir has a nice API then it’s possible to write very clean and understandable tests without using the @browser variable at all. Consider the example below as a result of that idea:

Does that appearance make the test less understandable than the version before? I don’t think so. I think that it makes it even more understandable and readable. The @browser variable doesn’t add much additional value there.

How to accomplish that solution technically? If you’d think in terms of some statically typed programming language (like Java for example) then you would start coding right away by adding some delegation methods like this:

Indeed, that solution would also work with Ruby. It’s just that it might feel weird for every other Ruby programmer who’d see the code written like that. In Ruby you can solve it much more elegantly by using special method called method_missing:

What this code does when the SpecHelper module is included into the describe block (and it is already done automatically, see part II) then all method calls which cannot be invoked directly will be sent to the @browser object (remember, method calls are actually messages sent to the objects) if it has a method with the called name. Similar technique is used by Rails, RSpec and many other Ruby libraries. This approach allows to create less code and have it behave more dynamically.

Since Kernel module has a method called p for outputting objects to the screen for inspection and Watir has a method p for finding paragraph elements from the html then you’d have to define at least one method explicitly by delegating the method call to the @browser object. I haven’t found any other conflicting methods yet. You can check out the changes of SpecHelper on the GitHub.

With this post i’m ending the “Writing less code in Watir/RSpec specs” series which show how not to use require and include statements in your specs, how not to open and close the browser specifically within each describe block and how not to have to write @browser variable everywhere.