From 9aa1d1d4007dd5a9d82520c37bc28fdcfd3168b0 Mon Sep 17 00:00:00 2001 From: Blaine Irvin Date: Thu, 15 Aug 2024 13:15:42 -0500 Subject: [PATCH] Test Pdf Concern --- lib/chromium/pdf.rb | 17 +++++++++++++---- test/chromium/test_pdf.rb | 26 ++++++++++++++++++++------ test/jobs/test_generate_pdf_job.rb | 9 +++++++++ 3 files changed, 42 insertions(+), 10 deletions(-) create mode 100644 test/jobs/test_generate_pdf_job.rb diff --git a/lib/chromium/pdf.rb b/lib/chromium/pdf.rb index 280a73d..3fca3fd 100644 --- a/lib/chromium/pdf.rb +++ b/lib/chromium/pdf.rb @@ -2,9 +2,12 @@ require_relative 'railtie' if defined?(Rails::Railtie) require_relative 'pdf/version' +require 'active_support/concern' module Chromium module Pdf + extend ActiveSupport::Concern + ## # @param unescaped_filename [String] The filename to save the PDF as. # @param print_url [String] The URL of the page you want to be processed. @@ -18,11 +21,17 @@ def generate_pdf!(unescaped_filename, print_url, arguments: ['--headless --disab Dir.mktmpdir do |path| filepath = "#{path}/#{filename}" - system("LD_PRELOAD='' #{chrome_path} --print-to-pdf='#{filepath}' #{arguments.join(' ')} #{print_url}") + chrome_print chrome_path, print_url, filename, filepath, arguments + end + end + + protected + + def chrome_print(chrome_path, print_url, filename, filepath, arguments) + system("LD_PRELOAD='' #{chrome_path} --print-to-pdf='#{filepath}' #{arguments.join(' ')} #{print_url}") - File.open(filepath) do |file| - yield file, filename - end + File.open(filepath) do |file| + yield file, filename end end end diff --git a/test/chromium/test_pdf.rb b/test/chromium/test_pdf.rb index 3d69442..ca67338 100644 --- a/test/chromium/test_pdf.rb +++ b/test/chromium/test_pdf.rb @@ -1,13 +1,27 @@ # frozen_string_literal: true require 'test_helper' +require 'test/jobs/test_generate_pdf_job' class Chromium::TestPdf < Minitest::Test - # def test_that_it_has_a_version_number - # refute_nil ::Chromium::Pdf::VERSION - # end + def test_job_includes_pdf_concern + assert_respond_to TestGeneratePdfJob.new, :generate_pdf! + end - # def test_it_does_something_useful - # assert false - # end + def test_generate_pdf_calls_chrome_print + job = TestGeneratePdfJob.new + job.stub :chrome_print, :ran do + assert_equal :ran, job.generate_pdf!('filename', 'url') + end + end + + def test_chrome_print_calls_file_open + job = TestGeneratePdfJob.new + File.stub :open, :ran do + result = job.send(:chrome_print, 'chrome', 'url', 'name', 'path', ['argument']) do |_file, filename| + assert_equal 'name', filename + end + assert_equal :ran, result + end + end end diff --git a/test/jobs/test_generate_pdf_job.rb b/test/jobs/test_generate_pdf_job.rb new file mode 100644 index 0000000..cccdf25 --- /dev/null +++ b/test/jobs/test_generate_pdf_job.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +class TestGeneratePdfJob + include Chromium::Pdf + + def perform(filename, url) + generate_pdf!(filename, url) + end +end