I'm looking forward to reuse code for bats unit tests on different environments. What I want to know if it's possible to have common @test code for both files in one place.
My first unit test file is to be run on my development environment:
#!/usr/bin/env bats
load 'test_helper/bats-support/load'
load 'test_helper/bats-assert/load'
setup() {
# Development environment
PROJECT_PATH="/d/develop/myproject"
}
@test 'check project path' {
cd $PROJECT_PATH
run git fetch origin
refute_output --partial 'fatal: not a git repository (or any of the parent directories): .git'
}
My second unit test file runs same test and is to be run on deployment or production environment:
#!/usr/bin/env bats
load 'test_helper/bats-support/load'
load 'test_helper/bats-assert/load'
setup() {
# Production environment
PROJECT_PATH="/var/myproject"
}
@test 'check project path' {
cd $PROJECT_PATH
run git fetch origin
refute_output --partial 'fatal: not a git repository (or any of the parent directories): .git'
}
As you see code for test is the same and only change $PROJECT_PATH
value on the setup function.
Thanks for taking your time to read this question.
There are several ways you could solve this:
setup
function and setPROJECT_PATH
outside the tests.PROJECT_PATH
variable required (and make the test fail if it is not set).ENVIRONMENT
outside the test(s) and setPROJECT_PATH
depending on the value ofENVIRONMENT
.(Please note that only the
setup
function needs to be changed for this, thecheck project path
@test function stays as-is)As talk is cheap and code speaks louder than words, here are some examples to demonstrate what I mean with each of these options:
Option 1. Set
PROJECT_PATH
outside the testsRemove
setup
entirely and setPROJECT_PATH
before calling BATS:Option 2. Set a sensible default
Set the production value as a default and allow it to be set from outside the test:
Option 3. Make
PROJECT_PATH
requiredTo abort and fail the test if
PROJECT_PATH
has not been set, replace your current setup with:Option 4. Use
ENVIRONMENT
Instead of depending on
PROJECT_PATH
directly, set an$ENVIRONMENT
when calling BATS and setPROJECT_PATH
based on that:Conclusion
Which solution is the best depends on what your desired setup is. Of course, cross-overs between these solutions is also possible. I'll leave that as an exercise tot the reader...