...

/

Helpers Should Be Tested and Testable

Helpers Should Be Tested and Testable

Learn why we should make helpers testable.

We'll cover the following...

Testing in helpers

We haven’t talked about testing yet. That’s because helpers are the first time so far we’ve written code that needs testing! Yes, the HTML templates we’ve created are real code, and we’re encouraged to treat them as such, but we don’t find a ton of value in testing them in isolation, especially when they don’t have much logic in them. We mostly want to ensure they render, which will be covered by system tests, which we’ll discuss at the end of the chapters on the view.

However, helpers are Ruby code, and the only way to know if they’re broken is to hope that a system test catches it. Because they are relatively easy to test, there is value in testing them in isolation. However, we have to be careful not to overly specify our tests for helpers because we don’t want our helpers’ tests to fail if we change immaterial things like styling.

The testing strategy we recommend for helpers is to write a test that:

  • Renders all possible versions of the helper so we know it will render.
  • Ensures that the string returned is HTML-safe.
  • Includes key content relevant to the behavior of the helper.

The first two criteria are easy to satisfy. The third is harder because we have to find the right ...