8

In my app i have runtime config initialization based on SCALA_ENV variable

In build.sbt i need to check if SCALA_ENV var is set, and if not set it to "test" but only for tests configuration, so that when

sbt test

is run locally on a developer machine without explicitly setting SCALA_ENV it would always use test environment configs

I tried

fork in test := true
envVars in Test := Map("SCALA_ENV" -> "test")

And then later somewhere in tests

System.getenv("SCALA_ENV")

But it always returns null...

Idon Lee
  • 105
  • 1
  • 1
  • 6

1 Answers1

18

I cannot reproduced you issue as desribed:

//build.sbt
name := "test-env"

version := "1.0"

scalaVersion := "2.11.8"

fork in Test := true

envVars in Test := Map("SCALA_ENV" -> "test")

libraryDependencies ++= Seq("org.scalactic" %% "scalactic" % "2.2.6", "org.scalatest" %% "scalatest" % "2.2.6" % "test")

And test code:

import org.scalatest.FlatSpec

class TestEnv extends FlatSpec {

  it should "get the correct env var value" in {
    assert("test" === System.getenv("SCALA_ENV"))
  }

}

If I run it with sbt test, it passes. Note, I use sbt 0.13.8, so if your version differs, you may face some wild bug. When I run it from IntelliJ Idea - it fails, and there is no wonder why - IDE uses its own test runner and skips sbt. As a workaround, you can set variable in Run/Debug Configurations -> Environment variables window.

Vitalii Kotliarenko
  • 2,947
  • 18
  • 26