Writing less code in Watir/RSpec specs, part II
In the first post of the series “Writing less code in Watir/RSpec specs” i’ve brought up a list of repetitions in the specs when writing user interface based tests with Watir (or something similar). The list itself was this:
- 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
So far i’ve covered the first repetition in the above list. In this post i’m going to write about the second and third one.
As you’ve probably noticed then you have to open up the browser in every test. You’ve probably doing it in the before :all block. And then, in the after :all block you usually want to close the browser. Here is an example of your typical spec file:
At least that’s how i’ve been doing it and it seems to be a good practice since it eliminates sharing of some of the state between example groups. And remember that dependencies in the tests are always bad!
Since these tasks have to happen with every example group then it is possible with RSpec to extract these statements out of your every spec file and create them only at one place. You can use Spec::Runner.configure for this task:
Write the code above into your spec_helper.rb file and don’t forget to load it from your environment.rb file automatically! By doing this, you’ll guarantee that browser will be opened before every example group is ran and closed afterwards.
When you have some global helper module which you’re including into every example group then you can include it with Spec::Runner.configure instead:
Just make sure that your SpecHelper module is loaded before trying to include it with config otherwise Ruby will throw an error about undefined constant SpecHelper :)
By using Spec::Runner.configure it’s possible to get rid of duplicate code quite easily. You can take a look at RSpec’s source at GitHub for more possibilities about using Spec::Runner.configure.
Check out how the spec_helper.rb and environment.rb will look like from the GitHub!




1 year ago