powershellpester

Pester 'It' or 'Context' array iteration


Pester 5.6.1 Powershell 7.4.5

Here's the deal. I have data that I am loading in the BeforeDiscovery. I can reference all the variables within at the Run stage...no problem there. Even the string arrays. What I cannot do...is loop over the string arrays. It just completely ignores them: enter image description here

The roles are definately there -> enter image description here

But it completely ignores the tests...it WILL break at tests that do not reference an array: enter image description here


Solution

  • All variables used with -ForEach has to be available in Discovery-phase, not just the source $account. Use a BeforeDiscovery-block inside the Describe to make $roles available. E.g.

    $c = New-PesterConfiguration
    $c.Run.ScriptBlock = {
        BeforeDiscovery {
            $account = @{
                'name' = 'one'
                'roles' = @('web', 'db')
            }, @{
                'name'  = 'two'
                'roles' = @('app', 'file')
            }
        }
        Describe 'Account <name>' -ForEach $account {
            BeforeDiscovery {
                [string[]]$serverroles = $_.roles
            }
            Context 'Has role <_>' -ForEach $serverroles {
                It 'Test 1' {
                    1 | Should -Be 1
                }
            }
        }
    }
    $c.Output.Verbosity = 'Detailed'
    $c.Run.PassThru = $true
    $r = Invoke-Pester -Configuration $c
    
    # Output
    Starting discovery in 1 files.
    Discovery found 4 tests in 26ms.
    Running tests.
    Describing Account one
     Context Has role web
       [+] Test 1 6ms (1ms|4ms)
     Context Has role db
       [+] Test 1 3ms (1ms|1ms)
    
    Describing Account two
     Context Has role app
       [+] Test 1 3ms (1ms|2ms)
     Context Has role file
       [+] Test 1 2ms (1ms|1ms)
    Tests completed in 153ms
    Tests Passed: 4, Failed: 0, Skipped: 0, Inconclusive: 0, NotRun: 0