I'm dealing with a lot of tests that all have the same structure as follows:
#[cfg(test)]
mod tests {
#[test]
fn test_sample() {
// create file, optionally write something inside
File::create(<FILE_NAME>).unwrap();
// test stuff with file
// delete file
fs::remove_file(<FILE_NAME>).unwrap();
}
}
My main concern is the sheer amount of duplicate code across all tests. I've tried using crates for creating a single global temp directory with the INIT.call_once()
pattern shown here, but it doesn't work because I can't declare a static
or const
variable at the module level without also initializing it. Obviously it would work if I created a separate temp directory in each test, but I'd like to create only one and then inject it inside the tests like rstest
does with fixtures.
Is it possible to achieve this kind of behaviour with temp directories? If not, I'd like to try the same thing with temp files, i.e. injecting them as fixtures. It should work, but I wanted to ask just in case. Or perhaps do you have other ideas for approaching this issue?