Setting environment variables when running Scala / SBT test suite
Asked Answered
O

2

12

I've created a Config object with a get method to return different strings based on the PROJECT_ENV environment variable. If PROJECT_ENV=test, then Config.get("somePath") returns some/path.csv, otherwise it returns s3a://some_bucket/a_file.csv.

object Config {

  def test(): Map[String,String] = {
    Map(
      "somePath" -> "some/path.csv"
    )
  }

  def default(): Map[String,String] = {
    Map(
      "somePath" -> "s3a://some_bucket/a_file.csv"
    )
  }

  def get(key: String, env: Option[String] = sys.env.get("PROJECT_ENV")): String = {
    val lookupMap = if (env == Some("test")) {
      List(default(), test()).flatten.toMap
    } else {
      default()
    }
    lookupMap(key)
  }

}

With Ruby / RSpec, I set the environment variable in the spec_helper.rb file with ENV['PROJECT_ENV'] = 'test'.

What is the scalatest equivalent of the spec_helper.rb file? How can I set an environment variable in Scala? This answer isn't sufficient.

My test suite runs successfully if I run $ PROJECT_ENV=test sbt test, but I want to simply run $ sbt test.

Ourself answered 6/10, 2016 at 17:16 Comment(1)
Why do you want to set environment variables inside sbt? Do you want to use it across applications?Morning
L
13

This question appears to have overlap with Set default env variable for test configuration in sbt .

The accepted answer over there worked well for me:

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

The key is to make sure to include the fork otherwise the same env in play when launching sbt gets used.

Loomis answered 30/3, 2017 at 15:41 Comment(0)
M
8

I don't have enough reputation to post this as a comment for Evan Closson's answer, but starting in SBT 1.10 "the syntax for scoping keys has been unified for both the shell and the build definitions to the slash syntax."

So the answer becomes

Test / fork := true
Test / envVars := Map("PROJECT_ENV" -> "test")
Mamelon answered 9/9, 2021 at 22:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.