sstephenson / bats

Bash Automated Testing System
MIT License
7.12k stars 517 forks source link

BATS with return value into variables #162

Closed bcv closed 8 years ago

bcv commented 8 years ago

input file being tested

function funcabc() { false }

I suppose have a test

@test "some name" {

var_abc=$(funcabc) [ $? -ne 0 ] }

This always fails. Cannot make it succeed or check for negatives as a test result.

ztombol commented 8 years ago

You're looking for the run command. It captures the status and the output of any command or function in $status and $output, respectively. I assume you want to assert output as well, thus you're capturing it in a variable.

#!/usr/bin/env bats

funcabc() {
  echo 'Error!'
  false
}

@test 'funcabc: return non-zero and display an error message' {
  run funcabc
  [ "$status" -ne 0 ]
  [ "$output" == 'Error!' ]
}

You should read the Readme again, because it's all in there. I can't stress this part right at the beginning enough:

Test cases consist of standard shell commands. Bats makes use of Bash's errexit (set -e) option when running test cases. If every command in the test case exits with a 0 status code (success), the test passes. In this way, each line is an assertion of truth.

Once you understand how simple Bats is, you can do some pretty neat things with it.

bcv commented 8 years ago

Thanks. Brilliant !!!