Reputation: 365
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?
Upvotes: 4
Views: 2374
Reputation: 921
Here is what i had to do:
#mine only happens during a foreach loop
$names = @("foo", "foo2")
Describe "Check name - all errors" {
foreach($rec in $names)
{
It "should have the correct value" {
$rec | Should -Be "foo"
}
}
}
#this is what i had to do to fix it :(
Describe "Check name - fixed" {
foreach($rec in $names)
{
It "should have the correct value" -TestCases @(
@{
rec = $rec
}
) {
$rec | Should -Be "foo"
}
}
}
Upvotes: 0
Reputation: 365
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!
Upvotes: 7