require 'spec_helper'
require_monitor 'monitor'

module RCS
  module Monitor
    describe ComponentChecker do

      before do
        turn_off_tracer(print_errors: false)
        RCS::DB::Config.instance.load_from_file
      end

      let(:subject) { described_class.new }

      before { expect(subject.mailer).to respond_to(:alert) }

      describe '#check_all' do

        context 'when there are two component on error' do

          before do
            factory_create(:status, name: "foo", status: Status::ERROR)
            factory_create(:status, name: "bar", status: Status::ERROR)
            factory_create(:status, name: "ser")
          end

          it 'sends one email' do
            expect(subject.mailer).to receive(:alert).once
            subject.check_all
          end
        end

        context 'when components are restored' do

          before do
            factory_create(:status, name: "foo", status: Status::ERROR)
            factory_create(:status, name: "ser")

            expect(subject.mailer).to receive(:alert).once
            subject.check_all

            ::Status.update_all(status: Status::OK)
          end

          it 'sends one mail and than nothing more' do
            expect(subject.mailer).to receive(:alert).once
            subject.check_all

            expect(subject.mailer).not_to receive(:alert)
            subject.check_all
          end
        end

        context 'when all components are ok' do

          before do
            factory_create(:status, name: "foo")
            factory_create(:status, name: "bar")
          end

          it 'does not send any emails' do
            expect(subject.mailer).not_to receive(:alert)
            subject.check_all
          end
        end

        context 'when an error occurs' do
          before do
            subject.mailer.stub(:restored?).and_raise
          end

          it 'does not raise any errors but log them with fatal level' do
            expect(subject).to receive(:trace).with(:fatal, /.*/)
            expect { subject.check_all }.not_to raise_error
          end
        end
      end
    end
  end
end
