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:
setupfunction and setPROJECT_PATHoutside the tests.PROJECT_PATHvariable required (and make the test fail if it is not set).ENVIRONMENToutside the test(s) and setPROJECT_PATHdepending on the value ofENVIRONMENT.(Please note that only the
setupfunction 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_PATHoutside the testsRemove
setupentirely and setPROJECT_PATHbefore 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_PATHrequiredTo abort and fail the test if
PROJECT_PATHhas not been set, replace your current setup with:Option 4. Use
ENVIRONMENTInstead of depending on
PROJECT_PATHdirectly, set an$ENVIRONMENTwhen calling BATS and setPROJECT_PATHbased 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...