From 0bee16071b4618824b5d23dca228dc87048ed37b Mon Sep 17 00:00:00 2001 From: etorreborre Date: Thu, 23 May 2024 19:33:23 +0200 Subject: [PATCH] feature: add a Scope trait to initialize variables in mutable specifications --- .../main/scala/org/specs2/execute/Scope.scala | 17 ++++++++++++++ .../scala/org/specs2/mutable/ScopeSpec.scala | 23 +++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 common/shared/src/main/scala/org/specs2/execute/Scope.scala create mode 100644 core/jvm/src/test/scala/org/specs2/mutable/ScopeSpec.scala diff --git a/common/shared/src/main/scala/org/specs2/execute/Scope.scala b/common/shared/src/main/scala/org/specs2/execute/Scope.scala new file mode 100644 index 000000000..cdc77e86b --- /dev/null +++ b/common/shared/src/main/scala/org/specs2/execute/Scope.scala @@ -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) } diff --git a/core/jvm/src/test/scala/org/specs2/mutable/ScopeSpec.scala b/core/jvm/src/test/scala/org/specs2/mutable/ScopeSpec.scala new file mode 100644 index 000000000..b9083659f --- /dev/null +++ b/core/jvm/src/test/scala/org/specs2/mutable/ScopeSpec.scala @@ -0,0 +1,23 @@ +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