|
| 1 | +require "rake" |
| 2 | +require "rails_helper" |
| 3 | + |
| 4 | +RSpec.describe "Logging Rake Tasks" do |
| 5 | + let(:rake) { Rake::Application.new } |
| 6 | + |
| 7 | + before do |
| 8 | + Rake.application = rake |
| 9 | + |
| 10 | + Rake::Task.define_task(:environment) |
| 11 | + my_task |
| 12 | + |
| 13 | + allow(rake).to receive(:top_level_tasks).and_return(%w[my_task]) |
| 14 | + |
| 15 | + load Rails.root.join("lib/tasks/logging.rake") |
| 16 | + |
| 17 | + rake["environment"].invoke |
| 18 | + end |
| 19 | + |
| 20 | + context "when the task runs successfully" do |
| 21 | + let(:my_task) { Rake::Task.define_task(my_task: :environment) } |
| 22 | + |
| 23 | + it "logs when the task starts and finishes" do |
| 24 | + expect(Rails.logger).to receive(:info).with("Task started", hash_including(:args)) |
| 25 | + |
| 26 | + expect(Rails.logger).to receive(:info).with("Task finished") |
| 27 | + |
| 28 | + rake["my_task"].invoke |
| 29 | + end |
| 30 | + |
| 31 | + it "logs the arguments passed in to the task" do |
| 32 | + expect(Rails.logger).to receive(:info).with("Task started", hash_including(args: %w[arg1 arg2])) |
| 33 | + |
| 34 | + allow(Rails.logger).to receive(:info).with("Task finished") |
| 35 | + |
| 36 | + rake["my_task"].invoke("arg1", "arg2") |
| 37 | + end |
| 38 | + end |
| 39 | + |
| 40 | + context "when the task raises an error" do |
| 41 | + let(:my_task) do |
| 42 | + Rake::Task.define_task(my_task: :environment) do |
| 43 | + raise StandardError, "Something went wrong" |
| 44 | + end |
| 45 | + end |
| 46 | + |
| 47 | + it "logs an error with the exception" do |
| 48 | + allow(Rails.logger).to receive(:info).with("Task started", hash_including(:args)) |
| 49 | + expect(Rails.logger).to receive(:error).with( |
| 50 | + "Task failed", |
| 51 | + { exception: ["StandardError", "Something went wrong"] }, |
| 52 | + ) |
| 53 | + |
| 54 | + expect { rake["my_task"].invoke }.to raise_error(StandardError, "Something went wrong") |
| 55 | + end |
| 56 | + end |
| 57 | + |
| 58 | + context "when the task is aborted with SystemExit" do |
| 59 | + let(:my_task) do |
| 60 | + Rake::Task.define_task(my_task: :environment) do |
| 61 | + raise SystemExit.new(0, "exit") |
| 62 | + end |
| 63 | + end |
| 64 | + |
| 65 | + it "logs an error with the exit message" do |
| 66 | + allow(Rails.logger).to receive(:info).with("Task started", hash_including(:args)) |
| 67 | + expect(Rails.logger).to receive(:error).with("Task aborted", { exit_message: "exit" }) |
| 68 | + |
| 69 | + expect { rake["my_task"].invoke }.to output(/exit/).to_stderr |
| 70 | + end |
| 71 | + end |
| 72 | +end |
0 commit comments