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