Created
February 18, 2022 23:07
-
-
Save tinacious/2b856953a37ef8f1293f877ea4934f5c to your computer and use it in GitHub Desktop.
A simple Ruby on Rails health check endpoint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ./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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ./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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ./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