Test the DOCX the Browser Sends Back: Rubyzip, Nokogiri and Minitest

Inspect browser-edited DOCX uploads with Rubyzip and Nokogiri, then use Minitest to check important paragraphs, styles and file limits.

Written by Technically reviewed by Jim Freeze · Reviewed

Browser editing introduces a second DOCX into a Rails workflow: the file downloaded from the editor after someone has made changes. Tests for the original template tell you very little about that copy. Open the returned archive with Rubyzip, read its XML with Nokogiri, and put the important expectations in Minitest. A saved letter with the right filename and MIME type can still be missing its payment clause.

Why the returned DOCX slips past many test suites

Take an engagement letter. A Rails app fills an engagement letter from Active Record data with the sablon gem, a template processor built for DOCX files and MailMerge fields. The account manager revises the payment terms before sending it. That saved version, rather than the freshly generated letter, becomes the record. In a typical suite the template gets the detailed assertions. Saving gets a successful response, a content-type check and perhaps a file-size assertion. None of those asks whether the payment terms survived.

Delete the payment paragraph in a fixture and run the existing suite. Does anything fail? In many apps, the honest answer is nothing. Rails’ ActiveStorage::Blob documentation describes a blob as metadata about a file plus a key for where it lives, and none of that metadata cares what the bytes say. Storage has no reason to distinguish two readable DOCX files merely because one has lost a clause.

That becomes easier to miss when editing happens entirely in the browser. Apryse’s walkthrough on how to embed DOCX editing in JavaScript describes an editor that does its work client-side, with no server, Office install or LibreOffice behind it, and returns the edited file through a single API call. The Rails action receives the result of those edits. It may have no record of the intermediate document state. Test the file at that boundary: what reached the server after Save, rather than what the server sent to the editor before the user started typing.

Give this boundary an owner. A front-end test can exercise the editor’s Save button while a template test checks the initial letter, yet neither necessarily inspects the bytes eventually stored against the client’s record. A regression fixture for that saved file joins the two.

Open a DOCX like any zip file

You can inspect the returned document without starting an office application. A DOCX stores XML parts inside a ZIP archive. The packaging rules come from ECMA-376, the Office Open XML standard, which is in its fifth edition. Microsoft’s reference on how a WordprocessingML document is put together even tells you to rename the file to .zip and look around. The main body is usually in word/document.xml. Inside it, a paragraph contains runs, and those runs contain text nodes. Rubyzip reads that part as a string; Nokogiri supplies the tree you query.

Read text across runs, not raw XML

Formatting divides text into runs. Consider a paragraph containing ‘Payment is due within thirty days.’ If only ‘thirty’ is bold, the words can occupy three separate runs. The phrase still reads normally in Word, but the raw XML has markup between its words. Searching the XML string for the complete phrase is therefore the wrong test. Collect the text nodes belonging to each paragraph, join them in document order, and assert against those strings. A change in how an editor splits the runs should then leave the assertion alone.

Start with the paragraph text. Nokogiri registers the namespaces declared on a document’s root on its own. In this example the document declares w on the root, so //w:p selects the paragraphs. For each paragraph, .//w:t selects its descendant text nodes. The final join reconstructs the text without bringing the XML tags along:

require "zip"
require "nokogiri"

MAX_XML = 5_000_000

def paragraph_texts(path)
  xml = Zip::File.open(path) do |zip|
    entry = zip.find_entry("word/document.xml") or raise "not a Word document"
    raise "document.xml is too large" if entry.size > MAX_XML
    entry.get_input_stream.read(MAX_XML + 1).to_s
  end
  raise "document.xml is too large" if xml.bytesize > MAX_XML
  Nokogiri::XML(xml).xpath("//w:p").map { |para| para.xpath(".//w:t").map(&:text).join }
end

For a saved fixture, call assert_includes paragraph_texts(path), FEE_CLAUSE, where FEE_CLAUSE is the complete paragraph you expect. The helper only reads the selected ZIP entry. MAX_XML limits that entry’s declared size and the bytes returned by the read; it is not an upload-size limit for the whole archive. This small helper reads w:t content only. Tabs, line breaks, tracked changes, headers and footers need separate handling if your documents rely on them.

Check styles and numbering, then stop

With the text recovered, decide which formatting carries meaning. For a directly applied heading style, inspect w:pPr/w:pStyle and its w:val, such as Heading1. Direct paragraph numbering appears under w:numPr. A missing number can leave a contract pointing to a clause the reader can no longer identify. These are checks on stored document structure; a convincing visual heading proves less. A heading may still appear in Word’s Navigation pane when its paragraph lacks a heading style. Microsoft 365 subscribers on Windows get automatically detected headings, which pick up bold or larger text on their own. That visual shortcut is useful for navigation, but it does not establish that the paragraph retained the style your template requires. Where styles supply numbering through inheritance, inspect the style and numbering parts too.

Avoid turning this into a snapshot of every XML attribute. An editor can add identifiers or change run boundaries without damaging the letter. Such differences produce noisy failures, and noisy assertions tend to be ignored. Text comparison needs a narrower policy as well. A non-breaking space can differ from a regular space in a string comparison, even when both appear as a gap on screen.

Normalize both strings first. String#unicode_normalize with :nfkc fixes the non-breaking space. Curly quotation marks are different. NFKC does nothing about curly quotation marks. A single line of code (String#tr) will replace them with straight quotation marks. Apply the same normalization to the expected clause and the document text. Agree with the template owner which differences matter before accepting extra transformations; punctuation can be meaningful in a contract.

Treat the upload as untrusted input

The client controls the uploaded bytes. Treat a file returned by your own editor as an upload, including when it arrives under the filename you originally supplied. In September, an advisory described a path traversal flaw in rubyzip versions before 3.4.0. The bug sits in Zip::Entry#extract, the method that writes entries out to disk, and it belongs to the family of flaws that Snyk’s 2018 Zip Slip research found in archive libraries across several languages.

Reading one named entry avoids any need to write its archive path to disk. The example in rubyzip’s README checks each entry’s size against a limit and caps how many entries it handles, and the same README warns that Zip::InputStream does no size checking of its own. Do not trust the declared uncompressed size on its own; the bounded read is a second check. Use rubyzip 3.4.0 or later and keep its security updates under review. For production, also cap the uploaded archive size and processing time. Reading one XML part does not validate the entire DOCX package.

Where the check belongs in a Rails app

This site’s tutorial on building a client document portal in Rails keeps every corrected upload as a new submission, so an approval always points at the exact file a reviewer saw. That is a useful point to run the inspection. A plain Ruby object can open the upload, run the checks and return an array of problems to the controller action that creates the submission. Write those problems for the account manager: ‘Schedule A heading lost its style’ is more actionable than an XPath or a failed boolean.

Everything described here fits inside Minitest’s standard assertions, mostly assert_includes and assert_empty. When assert_includes fails, it reports the collection it searched and the missing item. Your CI log then shows the missing sentence itself, say “Payment is due within thirty days.” Minitest’s changelog puts version 6 in December 2025. If an older helper still calls assert_equal with nil as its expected value, replace that assertion with assert_nil. Tests using Minitest’s extracted mock support need the minitest-mock gem. The paragraph check above does not need mocks.

Spend more time choosing fixtures than inventing assertion wrappers. This site’s comparison of Ruby and Python for web scraping makes the case for saved HTML with the expected output written down first. Use the same approach for Word files. Keep files the browser editor actually produced, including the odd ones, like a letter with half a page pasted from email, and load them with Rails’ file_fixture helper. Include a generated template as a baseline, then add files saved by the browser editor. A generated fixture never exercises that save operation. Keep the example which once lost a heading or split the fee paragraph; those are useful regression cases.

Start with one returned letter

A successful check establishes only the expectations you wrote. Finding the agreed fee clause does not establish that every sentence is correct. Nor does a structurally valid letter prove that its editor had permission to change the payment period. Keep the approval decision attached to the exact submission and handle permissions in the application.

Begin with a returned letter and one explicit expectation, such as the payment paragraph. Save a second copy with that paragraph removed and confirm the assertion fails for the right reason. Then try a harmless formatting change and confirm it still passes. That pair of fixtures tells you much more than another check that a DOCX file exists.