14

Say, I have a crate with a dependency that has an optional feature. Now this feature is mostly useful for testing, but the crate itself is a dependency for the whole code. Is it possible to instruct cargo to use the feature only for testing?

In my concrete example the optional feature depends on quickcheck, which I do not necessarily want to make a mandatory dependency for users of my crate.

ideasman42
  • 42,413
  • 44
  • 197
  • 320
Emilia Bopp
  • 866
  • 10
  • 20

1 Answers1

10

You can use a feature for a development dependency just like you would for regular dependencies. In the case of quickcheck, its only feature is collect_impls, so you can add this to your Cargo.toml:

[dev-dependencies.quickcheck]
version = "*"
features = ["collect_impls"]

N.B. This was actually done wrong inside of quickcheck. I just fixed it in 0.1.29.

BurntSushi5
  • 13,917
  • 7
  • 52
  • 45
  • So in my case quickcheck is itself a dev-dependency, but also a dependency of a feature of my dependency. In particular, I [implemented `Arbitrary` for the types in nalgebra](https://github.com/sebcrozet/nalgebra/pull/74). However, the compiler does not see the optional impls, when I try to depend on the feature as you suggested. I feel like I'm still missing something here. – Emilia Bopp Jan 10 '15 at 11:31
  • Never mind, my problem was that I was mixing a github dep on quickcheck with nalgebra's crates.io dep on it. Too subtle… – Emilia Bopp Jan 10 '15 at 12:33
  • In the case that the normal dependency isn't a semver-dependency (`version = "..."`), it works just to put the same path or the same Git repository URL. – timotree Mar 19 '20 at 20:13