From e5309d72d5debf4f9191704e2f8bd4eff7d3e603 Mon Sep 17 00:00:00 2001 From: Dick Davis Date: Thu, 21 Sep 2023 01:23:08 -0500 Subject: [PATCH] Add test coverage for controller concern --- lib/event_logger_rails.rb | 4 + .../event_logger_rails/loggable_spec.rb | 76 +++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 spec/app/controllers/concerns/event_logger_rails/loggable_spec.rb diff --git a/lib/event_logger_rails.rb b/lib/event_logger_rails.rb index c1bfa9f..7a74f7a 100644 --- a/lib/event_logger_rails.rb +++ b/lib/event_logger_rails.rb @@ -33,4 +33,8 @@ def self.logger def self.log(*tags, **params) logger.log(*tags, **params) end + + def self.reset + @logger = nil + end end diff --git a/spec/app/controllers/concerns/event_logger_rails/loggable_spec.rb b/spec/app/controllers/concerns/event_logger_rails/loggable_spec.rb new file mode 100644 index 0000000..a2a8dd9 --- /dev/null +++ b/spec/app/controllers/concerns/event_logger_rails/loggable_spec.rb @@ -0,0 +1,76 @@ +# frozen_string_literal: true + +require 'rails_helper' + +class DummyController < ActionController::Base + include EventLoggerRails::Loggable + + def test_one + log_event :info, 'event_logger_rails.event.testing' + head :no_content + end + + def test_two + log_event :info, 'event_logger_rails.event.testing', test: 'two' + head :no_content + end +end + +RSpec.describe EventLoggerRails::Loggable, type: :request do + let(:params) { { foo: 'bar' } } + let(:data_from_request) do + { + action: controller.action_name, + controller: controller.controller_name.camelcase, + method: request.method, + parameters: params.to_json, + path: request.path, + remote_ip: request.remote_ip + } + end + + let(:logger_spy) { instance_spy(EventLoggerRails::EventLogger) } + + before do + allow(EventLoggerRails::EventLogger).to receive(:new).and_return(logger_spy) + + Rails.application.routes.draw do + get :test_one, to: 'dummy#test_one', as: :test_one + get :test_two, to: 'dummy#test_two', as: :test_two + end + + EventLoggerRails.setup do |config| + config.logger_levels = %i[info] + end + end + + context 'without additional data provided' do + before { EventLoggerRails.reset } + + it 'calls the event logger' do + get(test_one_path, params:) + expect(logger_spy) + .to have_received(:log) + .with( + :info, + 'event_logger_rails.event.testing', + data_from_request + ) + end + end + + context 'with additional data provided' do + before { EventLoggerRails.reset } + + it 'calls the event logger' do + get(test_two_path, params:) + expect(logger_spy) + .to have_received(:log) + .with( + :info, + 'event_logger_rails.event.testing', + data_from_request.merge({ test: 'two' }) + ) + end + end +end