Expand description
A lightweight library for defining behavior-driven development (BDD) style
tests in external files and running them with cargo test
.
To write a test:
- Implement a
Handler
that interpretsBackground
andExample
sections defined in your spec file. - Write a test that calls
run
with aHandler
instance and a path that points to a spec file. You can also useglob_test
to derive one such test for each spec file in a given folder (including subfolders).
§Example
Here is a minimal example:
use spectest;
struct MevalHandler<'a> {
ctx: meval::Context<'a>,
}
impl<'a> MevalHandler<'a> {
fn new() -> Self {
Self {
ctx: meval::Context::new(),
}
}
}
impl<'a> spectest::Handler for MevalHandler<'a> {
type Error = String;
fn example(&mut self, example: &mut spectest::Example) -> Result<(), Self::Error> {
let Some(input) = example.when.get("input") else {
let msg = format!("missing `input` definition in the 'When' spec");
return Err(msg);
};
let input = match input.parse::<meval::Expr>() {
Ok(expr) => expr,
Err(err) => {
let msg = format!("cannot parse `input` expression `{input}`: {err}");
return Err(msg);
}
};
match input.eval_with_context(self.ctx.clone()) {
Ok(value) => {
example.then.insert("result", value.to_string() + "\n");
}
Err(err) => {
let msg = format!("cannot evaluate expression: {err}\n");
example.then.insert("result", msg);
}
}
Ok(())
}
}
#[spectest::glob_test("testdata/integration/**/*.md")]
fn test_meval(path: &str) {
let mut handler = MevalHandler::new();
spectest::run(path, &mut handler);
}
Assuming that the testdata/integration
folder contains a single called
calculator.md
, one can run the test against this file as follows:
# Expand the prefix to narrow the set of tested spec files
cargo test test_meval_
It is also possible to mass-rewrite failing tests after fixing/updating the
behavior of the meval
library under test as follows
REWRITE_SPECS=true cargo test test_calculator
For a more elaborated version that also updates the evaluation context
depending on the currently active Background
sections, see the
test/integration.rs
in the source repository.
Re-exports§
pub use core::async_run;
pub use core::run;
pub use core::AsyncHandler;
pub use core::Background;
pub use core::Error;
pub use core::Example;
pub use core::Handler;
Modules§
- core
- Core primitives and data types for BDD-like test definition and execution.
- md
- Support for BDD-files written in Markdown.