1

I have started using Pester to write test cases for my PowerShell scripts, but unfortunately, I am failing in even simple tests. For any test, if there is a variable in the It block the test fails even though it should pass.

Below is a simplified code:

Describe 'Basic Pester Tests' {
  It 'A test that should be true' {
    $true | Should -Be $true
  }
}
Describe 'should exist with variables test' {
    $someFile = 'C:\Scripts\EnableFlash.ps1'
    It "$someFile should exist" {
      $someFile | Should -Exist
    }
}

Describe 'should exist without variable test' {
  It "'C:\Scripts\EnableFlash.ps1' should exist" {
    'C:\Scripts\EnableFlash.ps1' | Should -Exist
  }
}

Describe 'compare for addition' {
  $a = 10; $b = 20
  It "test for variables" {
    $($a+$b) | Should -Be 30
  }
}

In the above code, the test should exist with variables test fails while the test should exist without variable test succeeds.

Output: Output of the script execution

I am using PowerShell 5.1 and Pester 5.1.1

Lieven Keersmaekers
  • 57,207
  • 13
  • 112
  • 146
Pramod
  • 391
  • 5
  • 21
  • 5
    In recent Pester versions, variables outside of the `It` are out of scope and cannot be referenced in your test. You should either place them in the `It` block or define them earlier inside a `BeforeAll`, etc, block.. Some info here: [Discovery and Run](https://pester.dev/docs/usage/discovery-and-run) – boxdog Mar 17 '21 at 09:53
  • And your next question on how to view the passing tests, you can use [this](https://stackoverflow.com/a/65421454/52598). If it is any consolation, I'm banging my head against the wall myself migrating to pester 5+. – Lieven Keersmaekers Mar 18 '21 at 14:31
  • @boxdog Would you mind submitting your comment as an answer? Just so this doesn't look unanswered anymore :) – Frode F. Jul 24 '23 at 09:49
  • 1
    @FrodeF. I've added it as an answer. – boxdog Jul 24 '23 at 10:44

1 Answers1

2

In recent Pester versions, variables outside of the It are out of scope and cannot be referenced in your test. You should either place them in the It block or define them earlier inside a BeforeAll, etc, block.

Some info here: Discovery and Run

boxdog
  • 7,894
  • 2
  • 18
  • 27