From 16de48d255515c85c5f7cabbcf2ac842736b0fc1 Mon Sep 17 00:00:00 2001 From: ChrisBAshton Date: Fri, 12 Jul 2024 11:47:13 +0100 Subject: [PATCH] Add `assets:get_id_by_legacy_url_path` rake task It seems unnecessarily laborious to have to run rails console commands (https://docs.publishing.service.gov.uk/manual/manage-assets.html#get-an-assets-id) in order to know what to pass to a rake task (https://docs.publishing.service.gov.uk/manual/manage-assets.html#redirect-an-asset). It should just be a rake task. --- lib/tasks/assets.rake | 7 +++++++ spec/lib/tasks/assets_spec.rb | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 spec/lib/tasks/assets_spec.rb diff --git a/lib/tasks/assets.rake b/lib/tasks/assets.rake index 63f447b8..ee81be3e 100644 --- a/lib/tasks/assets.rake +++ b/lib/tasks/assets.rake @@ -25,4 +25,11 @@ namespace :assets do asset = WhitehallAsset.find_by!(legacy_url_path: args.fetch(:legacy_url_path)) Rake::Task["assets:redirect"].invoke(asset.id, args.fetch(:redirect_url)) end + + desc "Get a Whitehall asset's ID by its legacy_url_path, e.g. /government/uploads/system/uploads/attachment_data/file/1234/document.pdf" + task :get_id_by_legacy_url_path, %i[legacy_url_path] => :environment do |_t, args| + legacy_url_path = args.fetch(:legacy_url_path) + asset = WhitehallAsset.find_by!(legacy_url_path:) + puts "Asset ID for #{legacy_url_path} is #{asset.id}." + end end diff --git a/spec/lib/tasks/assets_spec.rb b/spec/lib/tasks/assets_spec.rb new file mode 100644 index 00000000..4a23934b --- /dev/null +++ b/spec/lib/tasks/assets_spec.rb @@ -0,0 +1,32 @@ +require "rails_helper" +require "rake" + +RSpec.describe "assets.rake" do + before do + AssetManager::Application.load_tasks if Rake::Task.tasks.empty? + end + + describe "get_id_by_legacy_url_path" do + before do + task.reenable # without this, calling `invoke` does nothing after first test + end + + let(:task) { Rake::Task["assets:get_id_by_legacy_url_path"] } + + it "returns ID of asset by its legacy URL path" do + id = "abc123def456ghi789" + legacy_url_path = "/government/uploads/system/uploads/attachment_data/file/1234/document.pdf" + FactoryBot.create(:whitehall_asset, id:, legacy_url_path:) + + expected_output = <<~OUTPUT + Asset ID for #{legacy_url_path} is #{id}. + OUTPUT + + expect { task.invoke(legacy_url_path) }.to output(expected_output).to_stdout + end + + it "raises exception if no asset found" do + expect { task.invoke("foo") }.to raise_error(Mongoid::Errors::DocumentNotFound) + end + end +end