One of the hardest and most annoying things I find time and time again whenever I begin a new rails project is the inital setup and configurations of your development environment. Recently I began a new project where I was using Rails as an API, and I wanted to configure my RSpec to use helpers so my tests could stay DRY.
Configuring RSpec is not something I commit to memory, therefore I was spending some time online researching on how to do so, and the problem with online resources is that a lot of them are outdated or just simply don’t work. So after struggling for a bit on something that seemed so intuitive, I decided to document it here on my blog; so that I’ll have a direct reference for the next time I need to set up helpers for RSpec.
So here goes…
After the inital setup with
rspec-rails and running all the generators, the first thing is to include a
helpers folder in your spec. The path should look like
After doing that. Head into your
rails_helper generated by
rspec-rails and uncomment or add this line of code:
This will include all the files in your
helpers folder. Now in your helpers folder you can add any helpers you. An example of one I use quite often is:
This allows me to test the JSON response and response status quite easily, and I test these two things quite often as I’m fond of request specs; so it made sense to move these into their helpers. Now in order to use your helpers, all you would have to do is include
rails_helper at the top of every spec file: