bashtestingbats-core

BATS: Make variable persistent across all tests


I'm writing a BATS (Bash Automated Testing System) script and what I'd like is a variable to be persisted across all the tests. For example:

#!/usr/bin/env bats

# Generate random port number
port_num=$(shuf -i 2000-65000 -n 1)

@test "Test number one" {
    a = $port_num
}

@test "Test number two" {
    b = $port_num
}

When evaluated, a and b should equal each other. This doesn't work, though, because (according to the docs) the entire file is evaluated after each test run. Which means $port_num gets regenerated between tests. Is there a way/place for me to store variables that will be persisted for across all tests?


Solution

  • Export it as an environmental variable.

    # If ENV Var $port_num doesn't exist, set it.
    if [ -z "$port_num" ]; then
        export port_num=$(shuf -i 2000-65000 -n 1)
    fi
    

    In BATS you must call load to source a file.

    Put the above code in a file named port.bash in the directory you are executing from.

    Then before your functions, call load port. This will set up your $port_num once, and not change it.

    load port
    
    @test "Test number one" {
        a = $port_num
    }
    
    @test "Test number two" {
        b = $port_num
    }