Configuring Helpers in RSpec

// Jun 23, 2015

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 app/spec/helpers

After doing that. Head into your rails_helper generated by rspec-rails and uncomment or add this line of code:

Dir[Rails.root.join('spec/helpers/**/*.rb')].each { |f| require f }


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:

# app/spec/helpers.response_helpers.rb

module ResponseHelpers

  def parsed_body
    JSON.parse(response.body)
  end 

  def expect_response_code(code)
    expect(response.code).to eq(code)
  end

end

RSpec.configure do |config|
  config.include ResponseHelpers
end


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:

# app/spec/requests/...

require "rails_helper"

describe "GET /some_path" do
  it "returns 201 when succesful" do
    get "/some_path"
    expect_response_code("201")
  end
end

# => 1 example, 1 success