Testing | rust-crawler | Spatie       

 SPATIE  

rust-crawler
============

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Rust-crawler](https://spatie.be/docs/rust-crawler/v1)  Basic-usage  Testing

 Version   v1      

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

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

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

- [ Your first crawl ](https://spatie.be/docs/rust-crawler/v1/basic-usage/starting-your-first-crawl)
- [ Crawl responses ](https://spatie.be/docs/rust-crawler/v1/basic-usage/handling-crawl-responses)
- [ Using observers ](https://spatie.be/docs/rust-crawler/v1/basic-usage/using-observers)
- [ Collecting URLs ](https://spatie.be/docs/rust-crawler/v1/basic-usage/collecting-urls)
- [ Filtering URLs ](https://spatie.be/docs/rust-crawler/v1/basic-usage/filtering-urls)
- [ Testing ](https://spatie.be/docs/rust-crawler/v1/basic-usage/testing)
- [ Tracking progress ](https://spatie.be/docs/rust-crawler/v1/basic-usage/tracking-progress)

Configuring the crawler
-----------------------

- [ Concurrency &amp; throttling ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/crawl-behavior)
- [ Limits ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/setting-crawl-limits)
- [ Extracting resources ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/extracting-resources)
- [ Configuring requests ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/configuring-requests)
- [ Response filtering ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/handling-responses)
- [ Respecting robots.txt ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/respecting-robots-txt)

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

- [ JavaScript rendering ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/rendering-javascript)
- [ Custom link extraction ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/extracting-custom-links)
- [ Custom request handlers ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/custom-request-handlers)
- [ Crawling across requests ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/crawling-across-requests)
- [ Custom crawl queue ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/using-a-custom-crawl-queue)
- [ Graceful shutdown ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/graceful-shutdown)

 Testing
=======

###  On this page 

1. [ Matching and robots ](#content-matching-and-robots)
2. [ Statuses, headers and retries ](#content-statuses-headers-and-retries)
3. [ Run this project's checks ](#content-run-this-projects-checks)

Use `FakeFetcher` to test crawl behavior without HTTP requests. Routes return repeatable `FakeResponse` values or consumable sequences. Clones share routes and request records. Fakes never fall back to real networking.

```
use spatie_crawler::{CrawlEvent, Crawler, FakeFetcher, FakeResponse, FinishReason};

#[tokio::main]
async fn main() -> Result {
    let fake = FakeFetcher::new()
        .route("https://example.com/", FakeResponse::html(
            r#"One One again"#,
        ))
        .route("https://example.com/one", FakeResponse::html("Two"));

    let mut crawl = Crawler::builder("https://example.com")?
        .fetcher(fake.clone())
        .respect_robots(false)
        .retries(0)
        .max_depth(1)
        .build()?
        .crawl();
    let mut urls = Vec::new();
    let mut finished = false;
    while let Some(event) = crawl.next().await {
        match event {
            CrawlEvent::Page { page, .. } => urls.push(page.url.to_string()),
            CrawlEvent::Failed { error, .. } => panic!("unexpected failure: {error}"),
            CrawlEvent::Finished { reason, error, .. } => {
                assert_eq!(reason, FinishReason::Completed);
                assert!(error.is_none());
                finished = true;
            }
            _ => {}
        }
    }
    urls.sort();
    assert_eq!(urls, ["https://example.com/", "https://example.com/one"]);
    assert_eq!(fake.requests().len(), 2);
    assert!(finished);
    Ok(())
}
```

This checks fragment deduplication and the depth boundary. For an application test, use `#[tokio::test] async fn ...` instead of a standalone `main`.

Matching and robots
-----------------------------------------------------------------------------------------------------------------

Exact routes match serialized URLs, including trailing slashes and query ordering. `https://example.com` becomes `https://example.com/` when parsed. Patterns containing `*` match arbitrary substrings at that position; the full pattern must match, and the first registered route wins. Register specific routes before broad fallbacks.

Unlike PHP's fake handler, unmatched or exhausted routes return explicit request errors, not automatic 404 responses. Robots requests are not special-cased. Either disable robots for tests unrelated to them, as above, or add a `https://example.com/robots.txt` route. Use a 404 fake response there to represent a missing robots file.

Statuses, headers and retries
---------------------------------------------------------------------------------------------------------------------------------------------

```
use spatie_crawler::{FakeFetcher, FakeResponse};

fn fixtures() -> spatie_crawler::Result {
    Ok(FakeFetcher::new()
        .route("https://example.com/robots.txt", FakeResponse::new("").status(404))
        .sequence("https://example.com/temporary", [
            FakeResponse::html("Busy").status(503).header("retry-after", "0")?,
            FakeResponse::html("Recovered"),
        ])
        .route("https://example.com/private", FakeResponse::html("Forbidden").status(403))
        .route("https://example.com/network-error", FakeResponse::error("connection reset")))
}
```

`FakeResponse::html()` sets an HTML content type. `new()` does not. `header()` appends a header, including repeated values. A `.route()` response repeats indefinitely; `.sequence()` consumes one entry per fetch and errors when exhausted. Disable retries for tests not concerned with them, or provide enough sequence entries. Inspect `fake.requests()` to check URLs, headers, byte limits and timeouts.

The fake replaces transport, so it does not simulate cookies, redirects or DNS enforcement. Use local HTTP fixture servers to test those behaviors. The repository's transport tests demonstrate this pattern.

Run this project's checks
---------------------------------------------------------------------------------------------------------------------------------

```
cargo fmt --all -- --check
cargo clippy --locked --all-targets -- -D warnings
cargo test --locked --all-targets
cargo test --locked --doc
RUSTDOCFLAGS='-D warnings' cargo doc --locked --no-deps
```

`cargo test --doc` checks the Rust examples in this guide as well as the README. Examples that would contact websites are compile-only. The network-free crawl example above also runs its assertions.

Normal tests use fixtures and need no external website, browser or Cloudflare credentials. The optional real-Chromium test runs with `cargo test --locked --test rendering -- --ignored`. See [JavaScript rendering](../advanced-usage/rendering-javascript) before changing browser sandbox settings.

 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)
