Recently I was writing code to an API and I noticed that I always wrote something like:
expect(JSON.load(response.body)["data"]["posts"]).to eq "XXX" expect(JSON.load(response.body)["data"]["authors"]).to eq "XXX"
If you notice you see that:
expect().to eqis part of any test, so we need it;
JSON.load(response.body)["data"]is too long to write and it is not a syntax for tests;
I was introducing automated test to the company I needed to make it as easy as possible to read/write to people that know about it but not used to write.
I wrote this code:
module MyApp module Helpers def json_response JSON.load(response.body) end def api_response json_response["data"] end end end RSpec.configure do |config| config.include MyApp::Helpers end
MyApp usually is the same module in
config/application.rb in case of a Rails app.
There are two method, first because sometimes we just need the json response and the other one is a normal response from our api.
Posts in this series
- Learning Python using automated test, Sep 2 2014;
- How to create helper methods to RSpec (This post)
- Usefull Gems for testing a Ruby and Ruby on Rails app, Mar 13 2018;