Testing PDFs | laravel-pdf-rust | Spatie       

 SPATIE  

laravel-pdf-rust
================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-pdf-rust](https://spatie.be/docs/laravel-pdf-rust/v1)  Basic-usage  Testing PDFs

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-pdf-rust/v1) 

  Testing PDFs    
- [ Introduction ](https://spatie.be/docs/laravel-pdf-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-pdf-rust/v1/support-us)
- [ Requirements ](https://spatie.be/docs/laravel-pdf-rust/v1/requirements)
- [ Installation &amp; setup ](https://spatie.be/docs/laravel-pdf-rust/v1/installation-setup)
- [ Questions and issues ](https://spatie.be/docs/laravel-pdf-rust/v1/questions-issues)
- [ Changelog ](https://spatie.be/docs/laravel-pdf-rust/v1/changelog)
- [ Testing ](https://spatie.be/docs/laravel-pdf-rust/v1/testing)
- [ About us ](https://spatie.be/docs/laravel-pdf-rust/v1/about-us)

Basic usage
-----------

- [ Creating PDFs ](https://spatie.be/docs/laravel-pdf-rust/v1/basic-usage/creating-pdfs)
- [ Responding with PDFs ](https://spatie.be/docs/laravel-pdf-rust/v1/basic-usage/responding-with-pdfs)
- [ Formatting PDFs ](https://spatie.be/docs/laravel-pdf-rust/v1/basic-usage/formatting-pdfs)
- [ Saving PDFs to disks ](https://spatie.be/docs/laravel-pdf-rust/v1/basic-usage/saving-pdfs-to-disks)
- [ Attaching PDFs to mails ](https://spatie.be/docs/laravel-pdf-rust/v1/basic-usage/attaching-pdfs-to-mails)
- [ Queued PDF generation ](https://spatie.be/docs/laravel-pdf-rust/v1/basic-usage/queued-pdf-generation)
- [ Testing PDFs ](https://spatie.be/docs/laravel-pdf-rust/v1/basic-usage/testing-pdfs)
- [ Setting defaults ](https://spatie.be/docs/laravel-pdf-rust/v1/basic-usage/setting-defaults)
- [ Protecting PDFs with a password ](https://spatie.be/docs/laravel-pdf-rust/v1/basic-usage/protecting-pdfs-with-a-password)

Drivers
-------

- [ Configuration ](https://spatie.be/docs/laravel-pdf-rust/v1/drivers/configuration)
- [ Customizing Browsershot ](https://spatie.be/docs/laravel-pdf-rust/v1/drivers/customizing-browsershot)
- [ Using the Cloudflare driver ](https://spatie.be/docs/laravel-pdf-rust/v1/drivers/using-the-cloudflare-driver)
- [ Using the DOMPDF driver ](https://spatie.be/docs/laravel-pdf-rust/v1/drivers/using-the-dompdf-driver)
- [ Generating PDFs on AWS Lambda ](https://spatie.be/docs/laravel-pdf-rust/v1/drivers/generating-pdfs-on-aws-lambda)
- [ Using the Chrome driver ](https://spatie.be/docs/laravel-pdf-rust/v1/drivers/using-the-chrome-driver)
- [ Using the Gotenberg driver ](https://spatie.be/docs/laravel-pdf-rust/v1/drivers/using-the-gotenberg-driver)
- [ Using the WeasyPrint driver ](https://spatie.be/docs/laravel-pdf-rust/v1/drivers/using-the-weasyprint-driver)
- [ Custom drivers ](https://spatie.be/docs/laravel-pdf-rust/v1/drivers/custom-drivers)

Advanced usage
--------------

- [ Creating PDFs with multiple pages ](https://spatie.be/docs/laravel-pdf-rust/v1/advanced-usage/creating-pdfs-with-multiple-pages)
- [ Using Tailwind ](https://spatie.be/docs/laravel-pdf-rust/v1/advanced-usage/using-tailwind)
- [ Extending with Macros ](https://spatie.be/docs/laravel-pdf-rust/v1/advanced-usage/extending-with-macros)
- [ Waiting for readiness ](https://spatie.be/docs/laravel-pdf-rust/v1/advanced-usage/waiting-for-readiness)
- [ Caching PDFs ](https://spatie.be/docs/laravel-pdf-rust/v1/advanced-usage/caching-pdfs)

 Testing PDFs
============

###  On this page 

1. [ Faked PDF contents ](#content-faked-pdf-contents)
2. [ assertSaved ](#content-assertsaved)
3. [ assertRespondedWithPdf ](#content-assertrespondedwithpdf)
4. [ assertBrowsershot ](#content-assertbrowsershot)
5. [ Simple assertion methods ](#content-simple-assertion-methods)
6. [ Queued PDF assertions ](#content-queued-pdf-assertions)

In your test, you can use `PdfFake` to fake PDF generation. Because the PDF generation is faked, your tests will run much faster.

```
use spatie_pdf::testing::PdfFake;

let fake = PdfFake::default();
pdf.defaults(pdf.builder().fake(&fake));
```

Faked PDF contents
--------------------------------------------------------------------------------------------------------------

While faking, nothing is rendered: no Chrome is started, and no request is made to a remote PDF service. Methods that hand you the raw bytes of a PDF, such as `base64()` and `generate_pdf_content()`, and mail attachments created with `to_mail_attachment()`, return a tiny valid PDF with a single blank page. That way, code that writes those bytes to disk, encodes them, or hands them to a PDF parser keeps working in your tests.

```
use serde_json::json;
use spatie_pdf::testing::PdfFake;

let fake = PdfFake::default();
pdf.defaults(pdf.builder().fake(&fake));

let content = pdf.view("invoice", json!({})).generate_pdf_content().await?;

// %PDF-1.7 ... a valid, blank, single page PDF
```

PDFs whose content you generate this way are recorded like any other faked PDF, so the view, text and browser-option assertions will take them into account. Views still render through the real MiniJinja engine in an application context; fake saves and queue calls do not write files or touch the queue.

assertSaved
-----------------------------------------------------------------------------------------

You can use the `assert_saved` method to assert that a PDF was saved with specific properties. You should pass it a callable which receives a `RecordedPdf` and a path. If the callable returns `true`, the assertion will pass.

```
fake.assert_saved(|pdf, _| {
    pdf.document.name == "invoice.pdf"
        && pdf.request.html.contains("Your total for April is $10.00")
});
```

If you want to assert that a PDF was saved to a specific path, use the path passed as the second parameter of the callable.

```
fake.assert_saved(|_, path| {
    std::path::Path::new(path) == storage_path.join("invoices/invoice.pdf")
});
```

assertRespondedWithPdf
--------------------------------------------------------------------------------------------------------------------------

The `assert_responded_with_pdf` method can be used to assert that a PDF was generated and returned as a response.

Imagine you have a route `download-invoice` whose handler returns this response:

```
use serde_json::json;

let response = pdf.view("pdf.invoice", json!({}))
    .name("invoice-for-april-2022.pdf")
    .download()
    .to_response().await?;
```

In your test for this route you can use `assert_responded_with_pdf` to make sure that a PDF was generated and returned as a download. You can even make assertions on the content of the PDF.

```
use serde_json::json;

let response = pdf.view("pdf.invoice", json!({}))
    .name("invoice-for-april-2022.pdf")
    .download()
    .to_response().await?;
assert_eq!(response.status(), 200);

fake.assert_responded_with_pdf(|pdf| {
    pdf.document.name == "invoice-for-april-2022.pdf"
        && pdf.download
        && pdf.request.html.contains("Your total for April is $10.00")
});
```

Use your application's HTTP test client to request `download-invoice` in place of calling the builder directly. The package supplies the PDF response and assertions, not a router or an HTTP test client.

### Asserting metadata

You can assert that a PDF was generated with specific metadata by inspecting the `document.metadata` property on the recorded PDF.

```
fake.assert_saved(|pdf, _| {
    pdf.document.metadata.as_ref().is_some_and(|metadata| {
        metadata.title.as_deref() == Some("Invoice #123")
            && metadata.author.as_deref() == Some("Acme Corp")
    })
});
```

assertBrowsershot
-----------------------------------------------------------------------------------------------------------

When you customize the underlying browser options with [`browser_options`](../drivers/customizing-browsershot), you can use the `assert_browser_options` method to verify that customization, without actually starting Chrome.

The closure you pass receives the serializable browser options. If the closure returns `true`, the assertion passes. The assertion runs against every saved PDF and PDF response that was faked. It also checks other faked output operations.

```
use serde_json::json;

pdf.view("invoice", json!({}))
    .browser_options(|options| {
        options.insert("scale".into(), json!(0.5));
    })
    .save(target_path).await?;

fake.assert_browser_options(|options| options.get("scale") == Some(&json!(0.5)));
```

The Rust bridge does not expose a Browsershot object. Remote browser configuration belongs to `PhpBridgeDriver::config`, rather than per-PDF options; see [customizing Browsershot](../drivers/customizing-browsershot).

`assert_browser_options` also honors configuration set on the default builder. Options registered via `PdfFactory::defaults` are carried over when you attach a fake, so they are passed to your assertion.

Simple assertion methods
--------------------------------------------------------------------------------------------------------------------------------

Beside the methods listed above, there are a few simple assertion methods that can be used to assert that a PDF was generated. They are meant to test code that generated a single PDF. The assertions will pass if any of the generated PDFs match the assertion.

If your code generates multiple PDFs, it's better to use the `assert_saved` method.

### assertViewIs

You can use the `assert_view_is` method to assert that a PDF was generated using a specific view.

```
fake.assert_view_is("pdf.invoice");
```

### assertSee

You can use the `assert_see` method to assert that a PDF was generated that contains a given string.

```
fake.assert_see(&["Your total for April is $10.00"]);
```

You can pass an array of strings to assert that all of them are present in the PDF.

```
fake.assert_see(&[
    "Your total for April is $10.00",
    "Your total for May is $20.00",
]);
```

### assertViewHas

You can assert that a PDF was generated that was passed a specific key in its view data by inspecting the recorded view.

```
assert!(fake.records().iter().any(|pdf| {
    pdf.document.view.as_ref().is_some_and(|view| view.data.get("invoice").is_some())
}));
```

Use `assert_view_has` to pass the expected value as well.

```
use serde_json::json;

fake.assert_view_has("invoice", &json!(invoice));
```

### assertSaved

You can use the `assert_saved` method to assert that a PDF was saved to the specified path.

```
fake.assert_saved(|_, path| {
    std::path::Path::new(path) == storage_path.join("invoices/invoice.pdf")
});
```

Queued PDF assertions
-----------------------------------------------------------------------------------------------------------------------

### assertQueued

You can use the `assert_queued` method to assert that a PDF was queued for generation. It accepts a callable.

```
fake.assert_queued(|_, path| path == "invoice.pdf");
```

With a callable for more detailed assertions:

```
fake.assert_queued(|pdf, path| {
    path == "invoice.pdf" && pdf.request.html.contains("Total")
});
```

### assertNotQueued

You can use `assert_not_queued` to assert that no PDFs were queued, or inspect the records to assert that a specific path was not queued.

```
// Assert nothing was queued
fake.assert_not_queued();

// Assert a specific path was not queued
assert!(!fake.records().iter().any(|pdf| {
    pdf.operation == spatie_pdf::testing::Operation::Queued("other.pdf".into())
}));
```

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
