Testing HTML strings returned from helpers

I heart assert_select. But when we’re testing helpers using ActionView::TestCase, we don’t have a response object available, and assert_select is usually used in the context of a response object. So you might think you can just pass a string of html to assert_select, but unfortunately that doesn’t work. So what’s a Rails developer to do?

You could use regular expressions. You could also vomit on your monitor and stab yourself in the eye. Luckily, there are a couple alternatives.

RSpec. I’m not really an RSpec guy, but it apparently does have support for testing html from helpers.

The helper_me_test plugin from Brian Landau of Viget Labs seems like an elegant and flexible alternative. It takes advantage of the fact that assert_select accepts an optional HTML::Node object as its first argument. I definitely recommend taking a look at that plugin, especially if you prefer hpricot. The plugin seems to have been spawned as a consequence of this thread on the Rails Lighthouse.

Ultimately I’ve chosen to write something custom, but really lightweight, which involves simply opening the String class and adding a to_node method that returns the string as an HTML::Node. I’ve gisted an example. It’s not as elegant as helper_me_test, but it’s so little code that I’ve decided it’s best for the particular app I’m working on.

Hopefully this helps someone.

Post a Comment

Required fields are marked *

*
*

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: