Expectest assertions helper in both unit and integration test

Hello,

Context

First, a bit of context.

Currently, some of my unit tests look like that:

#[test]
fn it_works() {
   assert!(some_string.contains(some_pattern);
   assert!(!some_string.contains(some_other_pattern);
}

My problem is that assertions are a bit hard to read. The second assertion is the opposite of the first but it's easy to miss.

So I've been trying to use expectest with custom assertions

 struct Contain {
     // ...
 }

 fn contain(suffix: &pattern) -> StringContains {
      // ...
}

impl<T> Matcher<T, ()> for Contain
where
    T: AsRef<str> + std::fmt::Display ,
{
    fn matches(&self, actual: &T) -> bool {
     actual.to_string().contains(&self.pattern);
    }
}

That way I can write tests like this and I'm happy:

#[test]
fn it_works() {
    expect!(some_string).to(contain(some_pattern))
   expect!(some_string).to_not(contain(some_other_pattern))
}

So far, so good, but now I want to use my contain help in integration tests too.

Things I've tried

1/ Using:

// in src/lib.rs
#[cfg(test)]
pub mod test_helpers() {
   // ...
}

does not work: integration tests do not seem to be able to see the code inside #[cfg(test]]` in the main crate - and if I'm not mistaken, this is by design.

2/ Create a workspace with two crates

# <root>/Cargo.toml
[workspace]
members = ["myapp", "expectest_helpers"]
# <root>/myapp/Cargo.toml
[dev-dependencies]
expectest_helpers = { path = "../expectest_helpers" }

This works but seems a bit overkill.

Any ideas?

That's how I'd do it.

You can try to #[cfg(feature = "test-helpers")] instead of #[cfg(test)], (adding test-helpers to the features of your crate), and then run the tests with cargo test --features test-helpers

OK. Thans for the pointers :slight_smile: