When we discuss writing tested code, many assume the methodology begins and ends with programming languages like Ruby, but the importance of testing code is rightfully adopted into nearly every aspect of software development. I use True, the Sass Testing Framework by Eric M. Suzanne, to write logical unit tests for the functions used in the responsive grid framework, Susy.
Return Full Width of a Grid from Custom Grid Settings
This is a function from the Susy One codebase that’s slightly simplified for demonstration purposes. For those less familiar with functions in Sass, check out Mason Wendell’s wonderful guide on writing Sass functions.
columns-width() excepts one parameter,
$columns, which defaults to
$total-columns if nothing is passed in.
$total-colums is part of Susy One’s customizable grid settings. When a developer starts a project with Susy,
$total-columns is set to
12, but she can specify any number of columns needed for the responsive grid. This function also references
$gutter-width which default to 4em and 1em respectively.
Given only defaults, we can read the return statement like this.
This is one way Sass can read
if statements and it returns 59em. Let’s take a look at how one could use True to write tests for this function. You start by wrapping all tests in the
test-module where we can define a test suite with True’s
True Test Example
@include report; is what sends test results to the console and outputs them in a unique stylesheet for reference.
Inside the test module, you pass
test() the name of the function in question so we know which tests fails if and when things go wrong.
This assigns the return value of
$test and assigns what we expect it to return to
$expect. With those values set, we can use
assert-equals() to determine if they match. It excepts three parameters: the value in question, the expected result, and a message for output when things break.
There are several other functions we can use to test output, including
True Test Results
While the tests are running and you edit your functions, True reports back with your test results. Here’s what Susy’s Susy One module currently reports in the terminal.
Some critics argue that testing CSS is overkill. While there are obvious reasons to run image diffs on CSS output for large applications, True offers more than just testing CSS output. It tests the functions and API designed in production software like Susy and Compass.