This page looks best with JavaScript enabled

Pester 5 scope issues and calling PSScriptAnalyzer

 ·  ☕ 2 min read  ·  ✍️ Javy de Koning

What is breaking in Pester 5

After the GA release of Pester 5 some of my tests started failing. You can find an overview of breaking changes on this GitHub issue as well as on the README here.

In Pester v4 the below example would work fine.

1$Foo = 'Bar'
2
3Describe "DescribeName $Foo" {
4    Context "ContextName $Foo" {
5        It "ItName $Foo" {
6            $Foo | Should -Be 'Bar'
7        }
8    }
9}

However, in version 5 $Foo no longer ‘leaks’ to the It block. This results in the following error:

1Describing DescribeName Bar
2 Context ContextName Bar
3   [-] ItName Bar 10ms (7ms|2ms)
4    Expected 'Bar', but got $null.

PSScriptAnalyzer tests in v4

In v4, you could just loop over the PSScriptAnalyzer rules as follows:

1Describe 'PSScriptAnalyzer analysis' {
2    Foreach ( $Rule in (Get-ScriptAnalyzerRule)) ) {
3        It "Should not violate rule: $($Rule.RuleName)" {
4            Invoke-ScriptAnalyzer -Path "..\module.psm1"` 
5            -IncludeRule $Rule.RuleName |
6            Should -BeNullOrEmpty
7        }
8    }
9}

How to do it in v5

In Pester v5, we need to handle this differently. I would suggest using TestCases like so:

1ModuleFolder
2├── tests
3|   └── PSSCriptAnalyzer.Tests.ps1
4└── module-to-test.psm1

Your PSSCriptAnalyzer.Tests.ps1 would look like this:

 1$Modules = Get-ChildItem (Split-Path $PSScriptRoot -Parent)`
 2-Filter '*.psm1'
 3
 4$Modules | ForEach-Object {
 5    Import-Module $_.FullName -Force
 6}
 7
 8if ($Modules.count -gt 0) {
 9    Describe 'PSScriptAnalyzer analysis' {
10        It "<Path> Should not violate: <IncludeRule>"`
11        -TestCases @(
12            Foreach ($m in $Modules) {
13                Foreach ($r in (Get-ScriptAnalyzerRule)) {
14                    @{
15                        IncludeRule = $r.RuleName
16                        Path        = $m.FullName
17                    }
18                }
19            }
20        ) {
21            param($IncludeRule, $Path)
22            Invoke-ScriptAnalyzer -Path $Path`
23            -IncludeRule $IncludeRule |
24            Should -BeNullOrEmpty
25        }
26    }
27}

This brings along some minor issues. Today for example, you cannot access a nested hashtable in the it statement, hence you would need to always flatten the object.

Find Pester on GitHub:

pester/Pester - GitHub


Javy de Koning
WRITTEN BY
Javy de Koning
Geek 🤓, Love sports 🏃‍♂️🏋️‍♂️, Food 🍛, Tech 💻, @Amsterdam ❌❌❌.