Testing Example Code In Your Jekyll Posts

submited by
Style Pass
2021-08-17 14:30:04

Blocks of code in blog posts and articles often contain errors. I see it frequently, in other people’s writing and my own. Code examples are usually not tested, or even run through a compiler/interpreter, so errors are not surprising.

I’d like my code examples to be as good as the real code that I write. Ideally, all code examples would have tests, which are run before the site is deployed, as part of a CI build process.

jekyll-include_snippet is a plugin for Jekyll that allows snippets of text to be included from other files. This allows code to be kept separately from the markdown, which makes it easier to test.

In the YAML frontmatter, specify the path to the code with snippet_source. In the markdown, use the include_snippet liquid tag to include bits of code.

Testing the code is no different to testing code in any other Ruby project. I’m using RSpec, but you could easily use another framework, like MiniTest.

Leave a Comment