Testing Liquid Blocks With assert_select

I’ve been looking at trying to write some Liquid tags for use as Mephisto plugins. I still have my doubts as to how productive it is to extend/work with Liquid, but at least I’m making some small headway.

I’d gotten as far as having some code working (there were no errors in the running of the test) but I needed to test more deeply: that I could actually render something useful.

To me, tests are essential as a means of proving I’m making progress, and actually writing code that works. This is even more useful in a relatively new environment (read: Mephisto and Liquid).

Thankfully, Rails already includes some great stuff for testing HTML templating (and our controllers), especially now with the recent addition of assert_select to core. By default, it works by reading the respone inside your functional and integration tests via Rails’ @response object. However, it will also work with an HTML::Node so to test our Liquid block renders correctly we just need to create an HTML document from it!

Our test looks something like this




12345678910
def test_should_see_one_image_in_template_results      template = Liquid::Template.parse(        "{% flickrphotostream %}          <img src='' alt='{{pic.title}}' />        {% endflickrphotostream %}"        )      root_node = HTML::Document.new(template.render).root      assert_select root_node, 'img[alt=my title]'    end

We assert that we find an image tag that with some alt text set to our picture’s title. All nice and simple.

I’ll work on getting the rest of the code written, now I have a way to test it! All that’s left is to beautify it up a little - that’s too much hook-up code I’ll need in each test for my liking :)