Skip to content

Pester - Adapt to pester 5 rules #88

@wztechde

Description

@wztechde

Description

Pester 5 has two rules to follow, when writing tests because of the new Discovery / Run paradigm (Pester 5 - Discovery and Run)

  • Put all your test-code into It, BeforeAll, BeforeEach, AfterAll or AfterEach.
  • Put no test-code directly into Describe, Context or on the top of your file, without wrapping it in one of these blocks.

Your example tests don't take these rules into account, specially the second rule (No code .. on the top of the file) - the whole module import code is outside of a codeblock.

Set-Location -Path $PSScriptRoot
#-------------------------------------------------------------------------
$ModuleName = 'MyModule'
#-------------------------------------------------------------------------
#if the module is already in memory, remove it
Get-Module $ModuleName | Remove-Module -Force
$PathToManifest = [System.IO.Path]::Combine('..', '..', '..', $ModuleName, "$ModuleName.psd1")
#-------------------------------------------------------------------------
Import-Module $PathToManifest -Force
#-------------------------------------------------------------------------

Describe the solution you'd like

Please put the module import code in your scaffolded tests into a separate code block, preferrably a BeforeAll block. This way, you'll present clean Pester 5 code to your users, keeping them from doing the hard work on their own.
The way you're scaffolding the test-files should make it easy to implement this little change (you're using plaster variables for the modulename - therefore you won't step into scope issues by putting the import code into a block).
But please keep nonetheless an eye on potential scope issues I didn't think of.

Describe any alternatives you've considered

I did it myself - example see below

Additional context

BeforeAll {
   #-------------------------------------------------------------------------
   Set-Location -Path $PSScriptRoot
   #-------------------------------------------------------------------------
   $ModuleName = 'MyModule'
   $PathToManifest = [System.IO.Path]::Combine('..', '..', '..', $ModuleName, "$ModuleName.psd1")
   #-------------------------------------------------------------------------
   if (Get-Module -Name $ModuleName -ErrorAction 'SilentlyContinue') {
      #if the module is already in memory, remove it
      Remove-Module -Name $ModuleName -Force
   }
   Import-Module $PathToManifest -Force
 }

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions