9

I am trying to implement RSpec/Jasmine like BDD framework in Powershell (or at least research the potential problems with making one).

Currently I am having problems with implementing simple before/after functionality. Given

$ErrorActionPreference = "Stop"

function describe()
    {
    $aaaa = 0;
    before { $aaaa = 2; };
    after { $aaaa; }
    }

function before( [scriptblock]$sb )
    {
    & $sb
    }

function after( $sb )
    {
    & $sb
    }

describe

the output is 0, but I would like it to be 2. Is there any way to achieve it in Powershell (short of making $aaaa global, traversing parent scopes in script blocks till $aaaa is found, making $aaaa an "object" and other dirty hacks:) )

What I would ideally like is a way to invoke a script block in some other scope but I don't have a clue whether it is possible at all. I found an interesting example at https://connect.microsoft.com/PowerShell/feedback/details/560504/scriptblock-gets-incorrect-parent-scope-in-module (see workaround), but am not sure how it works and if it helps me in any way.

TIA

5
  • Have you looked at Pester : github.com/scottmuc/pester Commented Jul 29, 2012 at 7:48
  • Yes, it is not quite like RSpec/Jasmine, probably because of the problems described above. I have a very limited experience with Pester, but IMHO Pester is a very limited framework, no after/before, no nested describes, broken matcher implementation etc. Commented Jul 29, 2012 at 7:51
  • 1
    Consider contributing then :) Commented Jul 29, 2012 at 7:52
  • I will definitely consider contributing, currently I am just evaluating the possibility of implementing a better version in PowerShell - it might be just impossible, and Pester is what it is because of the conscious design decisions made after considering PowerShell limitations. Commented Jul 29, 2012 at 7:56
  • My take on BDD framework for PowerShell: github.com/mbergal/Jester. Caution: work in progress Commented Nov 3, 2012 at 20:03

1 Answer 1

9

The call operator (&) always uses a new scope. Instead, use the dot source (.) operator:

$ErrorActionPreference = "Stop"

function describe()
    {
    $aaaa = 0;
    . before { $aaaa = 2; };
    . after { $aaaa; }
    }

function before( [scriptblock]$sb )
    {
    . $sb
    }

function after( $sb )
    {
    . $sb
    }

describe

Note the use of . function to invoke the function in same scope as where `$aaaa is defined.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.