1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use std::borrow::Cow;

use mruby::convert::FromMrb;
use mruby::eval::MrbEval;
use mruby::load::MrbLoadSources;
use mruby::top_self::MrbTopSelf;
use mruby::value::{Value, ValueLike};
use mruby::Mrb;
use mruby::MrbError;

pub fn init(interp: &Mrb) -> Result<(), MrbError> {
    interp.def_rb_source_file("mspec.rb", include_str!("mspec.rb"))?;
    for source in Sources::iter() {
        let content = Sources::get(&source).map(Cow::into_owned).unwrap();
        interp.def_rb_source_file(source, content)?;
    }
    Ok(())
}

#[derive(RustEmbed)]
#[folder = "$OUT_DIR/mspec/lib"]
struct Sources;

#[derive(Debug)]
pub struct Runner {
    specs: Vec<String>,
    interp: Mrb,
    enforce: bool,
}

impl Runner {
    pub fn new(interp: Mrb) -> Self {
        Self {
            specs: vec![],
            interp,
            enforce: true,
        }
    }

    pub fn add_spec<T: AsRef<[u8]>>(&mut self, source: &str, contents: T) -> Result<(), MrbError> {
        if !source.contains("/fixtures/") && !source.contains("/shared/") {
            self.specs.push(source.to_owned());
        }
        self.interp.def_rb_source_file(source, contents.as_ref())
    }

    pub fn run(self) -> Result<bool, MrbError> {
        init(&self.interp).unwrap();
        self.interp.def_rb_source_file("/src/spec_helper.rb", "")?;
        self.interp
            .def_rb_source_file("/src/test/spec_runner", include_str!("spec_runner.rb"))?;
        if let Err(err) = self.interp.eval("require '/src/test/spec_runner'") {
            println!("{}", err);
            assert!(!self.enforce);
        }
        let specs = Value::from_mrb(&self.interp, self.specs);
        self.interp
            .top_self()
            .funcall::<bool, _, _>("run_specs", &[specs])
    }
}

#[cfg(test)]
mod tests {
    use crate::mspec::Runner;

    #[test]
    fn mspec_framework_loads() {
        let interp = mruby::interpreter().expect("mrb init");
        // should not panic
        assert_eq!(Runner::new(interp).run(), Ok(true));
    }
}