Skip to content

Commit

Permalink
feature: add a Scope trait to initialize variables in mutable specifi…
Browse files Browse the repository at this point in the history
…cations
  • Loading branch information
etorreborre committed May 23, 2024
1 parent 75d1865 commit 21525f1
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
17 changes: 17 additions & 0 deletions common/shared/src/main/scala/org/specs2/execute/Scope.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package org.specs2.execute

/** This trait can be used in mutable specifications to provide setup values. For example:
* ```scala
* class MySpec extends mutable.Specification:
* "e1" in new MyScope:
* someValue === 1
*
* trait MyScope extends Scope: val someValue: Int = 1
* ```
*/
trait Scope

object Scope:
/** This Given transforms a Scope to a Result */
given scopeAsResult[S <: Scope]: AsResult[S] = new AsResult[S]:
def asResult(t: =>S): Result = AsResult.safely { Result.resultOrSuccess(t) }
25 changes: 25 additions & 0 deletions core/jvm/src/test/scala/org/specs2/mutable/ScopeSpec.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package org.specs2.mutable

import org.specs2.specification.core.Env

class ScopeSpec(env: Env) extends org.specs2.Specification:
def is = s2"""

A mutable specification can use the Scope trait to initialize values for each example $useScopeTrait
"""

def useScopeTrait =
val result = org.specs2.runner.TextRunner.run(new ScopeSpecification)(env).output
(result must contain("+ This is an example which succeeds")) and
(result must contain("x This is an example which fails"))

class ScopeSpecification extends org.specs2.mutable.Specification {
"This is an example which succeeds" in new SpecScope:
value === 1

"This is an example which fails" in new SpecScope:
value === 2
}

trait SpecScope extends org.specs2.execute.Scope:
val value: Int = 1

0 comments on commit 21525f1

Please sign in to comment.