Archive

Posts Tagged ‘rspec’

Using rspec-rails during gem development

December 15th, 2008

Update:

I been having all sorts of problems using this approach after updates in rspec and rspec-rails and no longer recommend using it!

The source code has been updated to use another approach in which I include a minimal Rails application in the gem, to run tests against. Until I get a chance to write a more complete post on this new approach take a look at the source, available at GitHub.

Not long ago I started using rspec and rspec-rails for testing in my Rails apps. I’ve quickly became hooked on Behaviour Driven Design (BDD) and feel it has boosted the quality (and readability) of my tests.

But when I wanted to move a view helper from one project into a gem for easy reuse in other apps it took me a while to figure out how to get the tests to run in isolation.

The main issue I had was the rspec-rails gem relying on there being a rails project present which of course isn’t the case with a stand-alone gem. Specifically, it wants to load the project’s ApplicationController which in turn will load a whole bunch of other stuff.

The second problem I ran into was how to write tests for helpers that output text with a non-output code block (i.e., <% … %>).

Let’s look at the stripped down version of the rspec for my boxed_content helper that wraps its containing block in a number of divs:

When testing gems I don’t rely on the specs to follow the directory layout defined by rspec-rails. Instead I pass the :helper type on line 3 so the created example group is a HelperExampleGroup.

As the boxed_content helper will not output text on its own I use eval_erb to execute it. This done in the method on lines 17-19. Putting it in a method makes the test code easier to read.

Ok. On to the spec_helper.rb where rspec and rspec-rails are set up:

The trick here is on line 5 where I create an ApplicationController class. This will load a bunch of stuff and allow us to continue with the rest of the require statements for rspec and rspec-rails. Lines 8-19 are copied from rspec-rails initialization.

Finally on line 21, my module containing the helpers i want to test, is loaded.

Resources

Rails , , ,