Skip to content

Instantly share code, notes, and snippets.

@etorreborre
Last active November 25, 2020 17:51
Show Gist options
  • Save etorreborre/6f781d265a70938b84320d2b23bfac67 to your computer and use it in GitHub Desktop.
Save etorreborre/6f781d265a70938b84320d2b23bfac67 to your computer and use it in GitHub Desktop.
Add async steps in specs2
import org.specs2.specification.create._
import org.specs2.control.producer.Producer._
/** How to add an async action after each example */
trait AfterEachAsync extends org.specs2.mutable.Specification:
override def map(fs: =>Fragments): Fragments =
super.map(fs.flatMap { f =>
if Fragment.isExample(f) then
emitAsync(List(f, step(afterAsync)))
else
emitAsync(List(f))
})
protected def afterAsync: Any
/**
This spec shows how it works.
It prints out something like
e1 specs2-3
after example 1 specs2-2
e2 specs2-5
after example 2 specs2-11
e3 specs2-2
after example 3 specs2-8
So that the execution of both examples and steps gets dispatched to different threads
but the intended order of having 1 example followed by 1 step, then 1 example etc...
is maintained
*/
class TestMutableSpec extends org.specs2.mutable.Specification with AfterEachAsync:
var i = 1
def afterAsync: Any =
Thread.sleep(500)
println("after example " + i + " " + Thread.currentThread.getName)
i = i + 1
"e1" >> { println("e1 "+Thread.currentThread.getName); success }
"e2" >> { println("e2 "+Thread.currentThread.getName); success }
"e3" >> { println("e3 "+Thread.currentThread.getName); success }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment