I have this pester script block. When I run it, the "Test1" fails, which is good. The second "Test2" fail, but I want it to pass. For pester 5 this are the recomandations:
`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.`
This explains why my "Test2" fails. But If I put my code in one the proposed blocks, then I will not be able to use TestCases.
Is there a way to solve the issue ?
Describe "Sample" {
$test = 1
$testCase = @(
@{var1 = $test; ExpectedResult = $true})
It "Test1" -Tag "Update" -TestCase $testCase {
param ($var1, $expectedresult)
$var1 | should -be $null
$test | should -be 1
}
it "Test2" -Tag "Fail" {
$test | should -be 1
}
}
As @Efie mentions, code to generate testcases are the common exeption to the rule. A new
BeforeDiscovery
-block was added in Pester 5.1 that you should use for this type of code.In general, you should rarely mix concerns regarding re-using
$test
in your test. Your testcases should include the required variables. Actually, that's how you would pass the variable from Discovery to Run to make it possible, by providing it as a testcase-value. In your example you've done that, so$var1
should be available in the test and should be equal to1
(same as$test
in Discovery).I often name the hashtable-key the same as the Discovery-variable (
test
in this scenario) to make the transfer feel seamless.