Setting up Rubocop and Rspec for Serverless Ruby

Running tests and static code analysis before deploying serverless Ruby functions

Posted by Ricardo Trindade on May 8, 2019

I'd like to share the configuration I'm currently using with the serverless framework to deploy functions written in Ruby. The setup works for AWS Lambda but also for other providers.

This requires you to install the serverless scriptable plugin.

I find that adding these checks is important as it gives you an extra security layer when deploying functions to production and also makes you follow the guidelines established by the Ruby community. So this is how the initial part of the serverless.yml file looks like.

With the plugin you can customize how the package is assembled, for example, you may need to run transcompilation and packaging only on some folders. In this case, we will just be using it to make sure that the tests are passing and that we're following Rubocop's rules before deploying.

The spec folder where the tests live, and the node_modules one are excluded to reduce the size of the deployment package, and also because we don't need any of those files to run the code in production

You'll need to have rubocop and rspec installed locally and also to have a .rubocop.yml file where you configure which rules you want to use. For this one, I'm inheriting the rules from rubocop-github. You can add any extra steps to the hook, and you can also use minitest instead of rspec.

The configuration is really simple and the cool thing about it is that it cancels the deployment process if either rubocop or rspec fails and no code is changed in production.