Extract common test functionality in RSpec

published on NOV 1, 2018

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)

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.

Tagged: Ruby Ruby on Rails RSpec

Cookies help us deliver our services. By using our services, you agree to our use of cookies.