RSpec and Block-Based View Helpers

Posted by Matt on October 22, 2008

Block-based view helpers are a great way to cut down on repetitive HTML chores and DRY up your view code. They are normally rather simple methods that basically stick some content in the middle of HTML code.

Here is a block-based view helper that I use in one of my applications:

Now we can call the “box” helper in a view:

and it will actually render this:

Pretty sweet, right?

It is until you go to spec out your views with RSpec. After some obligatory Googlin’ I didn’t find much. It seems as though the block doesn’t do it’s thing when RSpec calls it via the “render” call in your view specs.

So where does this leave us? Time for a custom Matcher;. Relax, it’s pretty easy, but it does involve working with a regular expression. Rubular; is a great place to work with your REfu in real time. I highly recommend using it for your Matcher#matches method.

First things first: Crack open that spec_helper.rb file and lets create a new Matcher module that will test our “box” helper:

You can now test the rendering of your block-based view helper via something like:

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

Comments