I have the following simple test in Pester:
# Name.Tests.ps1
$name = "foo"
Describe "Check name" {
It "should have the correct value" {
$name | Should -Be "foo"
}
}
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?
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:
Describe "Check name" {
BeforeAll {
$name = "foo"
}
It "should have the correct value" {
$name | Should -Be "foo"
}
}
Thanks to @Mark Wragg for pointing me to the right direction!