Since tests are just code, we can refactor it the same way we refactor our application classes. Many times we would need the same piece of code in the different tests so it would be nice to not repeat it over and over again.

Let’s say we have controller tests and we usually do something like this:

get :some_action

expect(JSON.parse(response.body)).to eq({'key' => 'value'})

it would be a common expectation when you have API controllers and return responses in JSON format. We can refactor it by using helpers. The first step is to create file in spec/support directory and create simple module with methods the same way we are creating files in app/helpers directory:

module ControllerHelpers
  def json_response

Now it’s time to make our helper available in controller specs. In order to do this we have to require helpers file in spechelper.rb or railshelper.rb file:

require 'support/helpers/controller_helpers'

and then let RSpec know that we want to make this helper methods available in specs:

RSpec.configure do |config|
  config.include(ControllerHelpers, :type => :controller)

Want to receive useful tips, information about new Ruby gems and articles on a daily basis? Make sure you follow me and say hello!

Since we want our helper to be available only in controller specs we can specify the type of specs where RSpec would include our methods. If you plan to have many helper methods you can load them all using this code:

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


We can now update our expectation and use json_response helper method:

expect(json_response).to eq({'key' => 'value'})

And that’s it.

Want to become a better Rails developer?
Download for free the Introduction Rails patterns book and dive into the world of refactoring and easy-testable Ruby code today.
Join over 1,000 developers already subscribed to my newsletter and download the book. You can unsubscribe anytime:

Subscribe and get the book!