diff --git a/src/PHPSpec2/Runner/Runner.php b/src/PHPSpec2/Runner/Runner.php index 6774f6f..4f5ac08 100644 --- a/src/PHPSpec2/Runner/Runner.php +++ b/src/PHPSpec2/Runner/Runner.php @@ -136,7 +136,7 @@ public function runSpecification(Node\Specification $specification) public function runExample(Node\Example $example, Matcher\MatchersCollection $matchers) { - $context = $example->getFunction()->getDeclaringClass()->newInstance(); + $context = $this->getExampleContext($example); $collaborators = new Prophet\CollaboratorsCollection($this->presenter); foreach ($this->getExampleInitializers() as $initializer) { @@ -231,4 +231,20 @@ final public function errorHandler($level, $message, $file, $line) // error reporting turned off or more likely suppressed with @ return false; } + + /** + * Returns an instance of the class in which context we run the example + * @param \PHPSpec2\Loader\Node\Example $example + * @return mixed + */ + private function getExampleContext(Node\Example $example) + { + if (null !== $example->getSpecification()){ + $declaringClass = $example->getSpecification()->getClass(); + } + else { + $declaringClass = $example->getFunction()->getDeclaringClass(); + } + return $declaringClass->newInstance(); + } }