Easy PhpStorm Live Template For PHPUnit Tests

Taking time to stop your work and create little helpers for repetitive tasks can really boost your productivity in the long run. I try to make it a point to streamline anything that I find annoying after a few encounters. Over time a lot of tiny wins become a huge gain in overall programming productivity.

Let me show you one of the productivity hacks I use when writing PHPUnit tests in PhpStorm.

I really like the way tests read when using annotations instead of prefixing the test function name with test_. If you’re not sure what I’m talking about.
I prefer this:

Over this:

I picked up this style from Jeffrey Way of Laracasts.
The only information expressed in the test name is what is being tested. I know it seems insignificant, but test files feel cleaner when they are structured in this way.

The annoying part…

The annoying part is that, while it’s easy to type out “test_it_can_do_this_amazing_thing()”. It gets annoying to type out “/** @test */”¬† every time before the function. Furthermore, for some reason, I am really slow when I need to type underscores between each word in the test name.

The surprisingly satisfying solution

PhpStorm has a feature called LiveTemplates. Basically, they are a way to create snippets of text that expand when you type a keyword and press the Tab key. They also have the additional benefit of programmable functionality you can specify.

In my editor, I created a template that expands to a test function when I type “@test” and press the Tab key. Once the template is created I can start typing and it will snake_case whatever I type so that I don’t have to add the _ manually. This makes creating a new test super convenient.

Here is a link to the template with instructions on how to set it up:
PhpStorm Live Template Gist

Here is a quick video of the final result:

2 replies on “Easy PhpStorm Live Template For PHPUnit Tests”

This is awesome, Dustin. Thanks for sharing! I made one modification to your template, I moved the $END variable outside of the function after the $NAME variable, that way after the function is created, it will hop back to the name, and it can be easily deleted (instead of having to press up 3 times on the arrow key to remove the extraneous line). But this is exactly what I was looking for. Again, I appreciate the share.


Leave a Reply

Your email address will not be published. Required fields are marked *