noobmaster69
noobmaster69

Reputation: 3115

Detecting environment variables in Ruby on Travis CI

I have a set of dotfiles that I am trying to test on Travis CI.

There are certain elements of the dotfiles that I don't want wish to test on Travis (like installing Homebrew apps). To detect if I'm in Travis I'm using the following:

if defined?($TRAVIS) && $TRAVIS != ''
  $TEST_ENV = true
else
  $TEST_ENV = false
end

print "TEST ENV: " + $TEST_ENV.to_s

where I detect the Travis environment variable and then echo out the result in the console.

However, I keep getting $TEST_ENV as false and cannot work out why.

Upvotes: 1

Views: 379

Answers (2)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84373

In Your Code, $TRAVIS is Always Undefined

There are a number of issues with your code. These include:

  1. $TRAVIS is a Ruby global, not an environment variable.
  2. The environment is never checked because you aren't calling ENV::[].
  3. In some cases, && may bind too tightly. The difference between && and and is largely in precedence, so you should use parentheses to separate multiple conditions unless you are sure of what the parser will see.
  4. In your current code, defined? $TRAVIS will always be false.

To test an environment variable, you could simply check the stringified value like so:

# Are you sure you need a global variable here? If not, remove the dollar sign.
$test_env = ENV['TRAVIS'].to_s.empty?

Note that an unset environment variable will be nil, so you'll want to call #to_s before #empty? if an unset variable and an empty string are logically equivalent for your use case. Otherwise, you'll want to explicitly handle nil.

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230356

$TRAVIS is not an environment variable, it's a global variable. Environment variable looks like this:

ENV['TRAVIS']

Upvotes: 2

Related Questions