The contains macro allows us to check the elements in a collection:
(fact "Check if a collection contains some elements"
[:bread :butter :lemon] => (contains [:bread :butter :lemon]))
(fact "The order of elements matters"
[:bread :butter :lemon] => (contains [:lemon :bread :butter]))
The test's auto-runner produces the following output:
==================================================================
Loading (testing-example.midje-tests)
FAIL "The order of elements matters" at (midje_tests.clj:48)
Actual result did not agree with the checking function.
Actual result:
[:bread :butter :lemon]
Checking function: (contains [:lemon :bread :butter])
The checker said this about the reason:
Best match found: [:lemon]
nil
FAILURE: 1 check failed. (But 10 succeeded.)
By default, the contains function will check the order of items and will fail if the order specified in the expected collection differs from the order of items in the tested collection. In the preceding test, the order that we provided (and expect) is as follows:
[:bread :butter :lemon]
If we are not interested in the order, but only in the membership in a collection, we can use theĀ :in-any-order modifier, as follows:
(fact "The order of elements matters in not taken into account"
[:bread :butter :lemon] => (contains [:lemon :bread :butter] :in-any-order))
This will produce the following output:
==================================================================
Loading (testing-example.midje-tests)
nil
All checks (11) succeeded.
Suppose that there are more elements in the collection, as follows:
(fact "Collection has more elements"
[:bread :butter :cake :lemon] => (contains [:bread :butter :lemon]))
The preceding tests will fail, as shown in the following code snippet:
==================================================================
Loading (testing-example.midje-tests)
FAIL "Collection has more elements" at (midje_tests.clj:53)
Actual result did not agree with the checking function.
Actual result:
[:bread :butter :cake :lemon]
Checking function: (contains [:bread :butter :lemon])
The checker said this about the reason:
Best match found: [:bread :butter]
nil
FAILURE: 1 check failed. (But 11 succeeded.)
We can use the :gaps-ok modifier to fix the failing test:
(fact "Collection has more elements"
[:bread :butter :cake :lemon] => (contains [:bread :butter :lemon] :gaps-ok))
This allows the test to pass, as follows:
==================================================================
Loading (testing-example.midje-tests)
nil
All checks (12) succeeded
We can also combine both modifiers together, as follows:
(fact "Collection has more elements and not in order"
[:lemon :bread :butter :cake] => (contains [:bread :butter :lemon] :gaps-ok :in-any-order))
With both modifiers in use, our last test passes, as follows:
==================================================================
Loading (testing-example.midje-tests)
nil
All checks (13) succeeded