Creating SBT Task to Publish Docker Containers Before Running Tests

If you are publishing Docker containers from SBT, you might need to publish containers before running them on tests. It would be nice to have a task that would automatically publish these containers and then run a single test, like sbt test-only. So that's what we are doing here:

So on your build.sbt:

val testOnlyParser = {  
  import complete.DefaultParsers._
  (token(Space) ~> token(StringBasic, "<test to run>"))
}

lazy val runtest = inputKey[Unit]("runtest")  

Then in your SBT project settings please define the following:

runtest in Test := Def.inputTaskDyn {  
    publishLocalAllDockerTask.value
    val value = testOnlyParser.parsed
    println(s"Run Test: $value")
    (testOnly in Test).toTask(s" $value")
  }.evaluated

And that should be it, so now you can sbt runtest <test> which will publish your docker container (through SBT native packager) and run the single test specified.

That should be it!

Now if you want to make sbt test behave as sbt docker:publishLocal test automatically (in case you forget like I did often), you just need to add the following to your SBT project settings:

test in Test := {  
    publishLocalAllDockerTask.value
    (test in Test).value
  }

Enjoy!