diff --git a/Functions/Assertions/PesterThrow.Tests.ps1 b/Functions/Assertions/PesterThrow.Tests.ps1 index 7131f91ba..cf44f8f59 100644 --- a/Functions/Assertions/PesterThrow.Tests.ps1 +++ b/Functions/Assertions/PesterThrow.Tests.ps1 @@ -95,3 +95,16 @@ InModuleScope Pester { } } } + +Describe 'Should Throw - Scope test' { + # This test can't be placed into an "InModuleScope Pester" block, because the whole internal Pester + # call stack becomes part of the chain between the test script and the script block that's passed + # to "Should Not Throw". This isn't a problem for any other InModuleScope situation; just when + # Pester is testing itself. + + It 'Dot-sources the script block' { + $result = 'Set in It scope' + { $result = 'Set in Should scope' } | Should Not Throw + $result | Should Be 'Set in Should scope' + } +} diff --git a/Functions/Assertions/PesterThrow.ps1 b/Functions/Assertions/PesterThrow.ps1 index 98bce68e7..6d16a91c0 100644 --- a/Functions/Assertions/PesterThrow.ps1 +++ b/Functions/Assertions/PesterThrow.ps1 @@ -9,8 +9,12 @@ function PesterThrow([scriptblock] $script, $expectedErrorMessage) { $Script:ActualExceptionWasThrown = $false try { - # Redirect to $null so script output does not enter the pipeline - & $script > $null + # Assign to $null so script output does not enter the pipeline + # Script block is dot-sourced so callers may do things like this: + # { $result = Do-Something } | Should Not Throw + # $result | Should Be 'Successful output test' + + $null = . $script } catch { $Script:ActualExceptionWasThrown = $true $Script:ActualExceptionMessage = $_.Exception.Message