Ray's Knowledge Base
Unlock

In parallel Rust tests inject env lookups instead of mutating the process environment

PreferenceVerified 4 Oct 2026Holds anywhere
Preference. A rule, why it holds, and how to apply it.

Rule#

Do not call std::env::set_var in tests. Pass an environment lookup function into the code under test.

Why#

The process environment is shared by parallel tests, so mutation races, and set_var is unsafe in edition 2024.

How to apply#

Give helpers a parameter such as impl Fn(&str) -> Option<String>; production passes |k| std::env::var(k).ok(), tests pass a closure over a map.

Also found by searching

  • std::env::set_var is unsafe in edition 2024
  • parallel rust tests race on environment variables
  • how do I test code that reads env vars in rust