Search code examples
scalaspecs2

specs2: Moving common Given into superclass


In Specs2, I am using Given/When/Then style with ScalaCheck in mutable specifications, and I have a commonly-used Given step that creates a ScalaCheck Gen object, and I would like to move it into a common superclass of all the tests that have that step. (Well, actually, into a trait, but maybe that doesn't make a difference.)

However, my tests have some quite intricate setup code which must be run in the correct order, and I already have quite a deep class hierarchy for my specs2 test code, and every trick I've tried so far to make things get executed in the correct order has failed to keep the order of execution the same. On the face of it, it seems weird that this would be so difficult, but of course I don't know how specs2 actually executes things in a situation like this, so I'm really just making guesses.

So my question is, how can I move a Given step into a superclass or trait, without affecting the order of execution in any significant way.


Solution

  • It's not rocket science - it's simply a matter of explicitly invoking the Given step after all the setup code has run. So you can put the Given step in a method, and call that method after the setup code.

    More complicated solutions won't necessarily work. Don't put it inside a step.