As bash doesn’t have first class functions, I’m simulating anonymous functions by passing a string to a function, which then gets evaluated by eval.
it() {
echo "$1" # prints the description of the spec
beforeEach # a setup function
eval "$2"
if (($? == 0)); then
# do something
fi
afterEach # a cleanup function
}
it "should echo something" '{
echo "something"
}'
This allows to write very concise tests (it defines a specification). Now I wonder if this is a valid use of eval.
EDIT
I am aware that the opening { and closing } are not need in the anonymous function string, it’s just that that way it resembles for something like Jasmine.
EDIT
The pseudo anonymous function is actually a test, which means at the end of the test, there is something like
[[ var == 'foo' ]]
or
((i > 10))
i.e. some sort of test (or assert, in XUnit terms). It never needs to return anything than the return code which then gets evaluated, and if the return code is 0 (success), the description is printed in green, otherwise red (the test failed).
If it gets the job done and you (and ideally others) understand how it works, absolutely.
I’ve been writing similar code for test case automation more than once or twice, but I admit it can get pretty hairy, especially if you start simple and then allow it to grow organically.
For what it’s worth, I would like to suggest a stylistic improvement;
or if the “something” is a simple command, plain old
Having said that, it might be better if you can avoid the
evalaltogether, but this depends on your test cases.