2

I have a binary Rust project which uses the workspaces to manage sub-crates.

Directory structure

/myapp
  Cargo.toml
  /src
  /tests
    test.rs
  /crates
    /printer
      Cargo.toml
      /src

myapp/Cargo.toml

[package]
name = "myapp"

[workspace]
members = ["crates/printer"]

Inside of test.rs I can compile extern crate myapp; to pull in the parts of the application that are exposed in src/lib.rs. This works as expected.

However, when attempting to compile extern crate printer; it errors that it cannot find it. I've confirmed that the printer package is correctly placed in the top-level Cargo.lock file.

How do I include my sub-crates into the /tests directory at the top level?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
lovelikelando
  • 7,593
  • 6
  • 32
  • 50

1 Answers1

3

There's nothing special about workspaces or even the concept of tests. If you want to use a crate in Rust code, you have to add it as a dependency:

[dependencies]
printer = { path = "crates/printer" }

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • So, I did try that and it seemed to mess up the shared dependency nature of workspaces. When I add in the printer crate as a dependency, I then need to add its dependencies to its `Cargo.toml`. It stops sharing the dependencies with the root crate. – lovelikelando Feb 06 '18 at 02:47
  • 2
    @garrettmaring *I then need to add its dependencies to its Cargo.toml* — yes; that's how it is **supposed** to work. The point of a workspace is to ensure that all the members have the same version of the compiled dependencies (a unified **Cargo.lock**). Each crate in a workspace is supposed to define its own **Cargo.toml**; otherwise where would you define things like the crate name? You may wish to re-read the [Cargo docs about workspaces](https://doc.rust-lang.org/cargo/reference/manifest.html#the-workspace-section). Perhaps file a bug if you think the docs are unclear. – Shepmaster Feb 06 '18 at 03:04
  • 2
    If a dependency is only used in tests, it should be defined in `[dev-dependencies]` rather than in `[dependencies]`. – Francis Gagné Feb 06 '18 at 05:35