Search code examples
unit-testingtestingclojuremidje

reusing setup and teardown with against-background in midje


I have a number of midje facts that have setup/teardowns that are almost, but not quite, entirely the same.

(against-background [(before :contents (setup!)) (before :contents (data)) (before :facts (set-access)) (after :contents (teardown!)]
  (facts "about this thing i am testing "
    ; ...
  ))

(against-background [(before :contents (setup!)) (before :contents (data)) (before :facts (set-other-access)) (after :contents (teardown!)]
  (facts "about this other thing i am testing "
    ; ...
  ))

I would like to wrap the backgrounds into something reusable and preferably paramterizable so I can reuse them, but having trouble doing so. Midje tells me anything other than the above is not the expected background form.


Solution

  • Midje does not have the ability to do what you ask built into it. If you would like this, consider adding it as an issue here: https://github.com/marick/Midje/issues?sort=updated&direction=desc&state=open&page=1

    A solution is to create your own macro to do this. (untested)

    (defmacro against-my-background [docstring & body]
      `(against-background [(before :contents (setup!)) 
                            (before :contents (data)) 
                            (before :facts (set-access)) 
                            (after :contents (teardown!)]
         (facts ~docstring
           ~@body )))
    
    ;; usage
    (against-my-background "about this thing i am testing"
      (fact (foo) => :bar)
      (fact (foo) =not=> :baz))