Pester: Cannot access parent scoped variable

Question:

I have the following simple test in Pester:

So when I navigate to the folder containing the test script and run Invoke-Pester, I was expecting the test to pass. Instead, I get the following error:

[-]Check name.should have the correct value. Expected 'foo', but got $null...

Any idea why this fails and why $name is set to null in the It block – shouldn’t $name still be set to foo as it’s from the parent scope?

Answer:

There are new rules to follow for Pester v5 and one of them is the following (https://github.com/pester/Pester#discovery–run):

Put all your code into It, BeforeAll, BeforeEach, AfterAll or
AfterEach. Put no code directly into Describe, Context or on the top
of your file, without wrapping it in one of these blocks, unless you
have a good reason to do so.

All misplaced code will run during Discovery, and its results won’t be
available during Run.

So placing the variable assignment in either BeforeAll or BeforeEach within the Describe block should get it working:

Thanks to @Mark Wragg for pointing me to the right direction!

Source:

Pester: Cannot access parent scoped variable by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply