Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default env variable for test configuration in sbt

Tags:

scala

sbt

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...

like image 951
Idon Lee Avatar asked May 19 '16 17:05

Idon Lee


1 Answers

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.

like image 114
Vitalii Kotliarenko Avatar answered Nov 25 '22 03:11

Vitalii Kotliarenko