Skip to content

Instantly share code, notes, and snippets.

@tinacious
Created February 18, 2022 23:07
Show Gist options
  • Save tinacious/2b856953a37ef8f1293f877ea4934f5c to your computer and use it in GitHub Desktop.
Save tinacious/2b856953a37ef8f1293f877ea4934f5c to your computer and use it in GitHub Desktop.
A simple Ruby on Rails health check endpoint
# ./app/controllers/health_controller.rb
class HealthController < ApplicationController
skip_before_action :authenticate!
def index
current_time_str = ActiveRecord::Base.connection.execute("SELECT CURRENT_TIME;").first["current_time"]
current_time = current_time_str.to_datetime
render json: {
success: true,
now: current_time.utc
}
rescue => e
puts e
Rollbar.error(e) # or another error monitoring service
render json: {
success: false,
}, status: 500
end
end
# ./spec/controllers/health_controller_spec.rb
require 'rails_helper'
RSpec.describe HealthController do
describe '#index' do
def go!
get :index
end
it_behaves_like 'ok'
it 'returns valid JSON' do
go!
expect(response_json[:success]).to eq(true)
end
it 'gets the date from Postgres' do
go!
expect(response_json[:now]).not_to be_nil
expect(response_json[:now].to_datetime).not_to be_nil
end
end
end
# ./spec/support/shared_examples.rb
RSpec.shared_examples 'ok' do
it 'returns OK' do
go!
expect(response).to be_ok
expect(response_json[:error]).to be_nil
end
end
# ./spec/support/helpers/test_helpers.rb
module Helpers
module Test
def response_json
JSON(response.body).with_indifferent_access
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment