Hey fellow Rustaceans!
In the directory of my Ruby on Rails project I can run rails c
and then run any statement. For example: calling a public method I've just written. Is there anything similar for Rust? It would make quick sanity testing so much easier!
Even if something like that isn't possible, I'd still love to hear some tips on how to run quick tests on new code I write.
P.S.:
Here's a real situation I've had today. I've added a new function in my_module
:
use nalgebra::Vector2;
pub fn vector2_iter(from: Vector2<i64>, to: Vector2<i64>) -> impl Iterator<Item = Vector2<i64>> {
(from.x..=to.x).flat_map(move |x| (from.y..=to.y).map(move |y| Vector2::new(x, y)))
}
The rust-analyzer didn't complain but I wanted to ensure the function did what I wanted it to do. With the Rails console functionality it would have been as easy as running:
crate::my_module::vector2_iter(nalgebra::Vector2::new(0, 0), nalgebra::Vector2::new(1, 1)).collect::<Vec<_>>())
And hoping to see [[[0, 0]], [[0, 1]], [[1, 0]], [[1, 1]]]
outputted. It would have taken 5 seconds. But instead I had to write a test that I'll only use once:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
println!("{:?}", vector2_iter(Vector2::new(0, 0), Vector2::new(1, 1)).collect::<Vec<_>>());
}
}
Of course, with LLM-powered code completion, this didn't take that long. But it still took longer than simply running the statement in a console. Then in VSCode I simply clicked a button to run it (this saved time over typing cargo test -- --exact my_module::test
)
But then the real reason this approach is bad for quick testing:
error: could not compile `project` (bin "project" test) due to 1 previous error; 1 warning emitted
Meaning, that if there's an issue somewhere else in my project (not in my_module
), tests don't work at all! This wouldn't be an issue using the Rails console - only the code that's run needs to work.
Alternatively, appending the statement to the beginning of main()
and running the entire project (thus avoiding having to write the test boilerplate) only works for some projects, and it still doesn't work if the project doesn't compile.