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
    JSON.parse(response.body)
  end
end

Now it’s time to make our helper available in controller specs. In order to do this we have to require helpers file in spec_helper.rb or rails_helper.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)
  ...
end

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}

Refactoring

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

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

And that’s it. You can also read guide how to write good tests.

Download free RSpec & TDD ebook

Do you want to earn more or jump to the next level in your company? Do you know that testing skills are one of the most desired skills? There is only first step: start testing and do it right. My ebook can help you. Subscribe to the newsletter to get a free copy of the book.

One Comment

  1. Pingback: 週刊Railsウォッチ(20180209)RubyにMJIT初マージ、高速JSON API gem、Railsにparallel-testingブランチほか

Leave a Comment

Your email address will not be published. Required fields are marked *