param (
[Parameter()]
$ParameterPath = "Approved-rule.json"
)
# BeforeDiscovery {
# ## Store the data from the json file to be re-used
# $parameterFile = Get-Content $ParameterPath
# }
Describe "Rules validation (Base)" -Tag "CI" {
BeforeAll {
$parameterFile = Get-Content $ParameterPath
$incommingParamObject = $parameterFile.Parameters
$rules = $parameterFile.Parameters.Test.value
}
Context "Validate for Parameter" {
It "File should not be null or empty" {
Write-Host "rule: $($rules)"
$rules | Should -Not -BeNullOrEmpty
}
}
}
When i am running the pester script the rule is coming as empty value. How does the scoping in pester works does the BeforeAll block be a global or i should add BeforeDiscovery?
Another question where should I add a Inline function ?
When running the above pester code all the variables are getting printed null. The file exists with correct path.
Solution:
To resolve this issue, you should define your functions in the appropriate block based on where you need to use them. If you need to use a function/varaible in an It block, you should define it in a BeforeAll block. If you need to use a function in a Describe or Context block, you should define it in a BeforeDiscovery block.
You have a typo in your
It
statement, should be$rules
instead of$rule
and you're missingConvertFrom-Json
in yourBeforeAll
block, then your code should work fine.Using this Json as an example:
Approved-rule.json
And the Pester test code:
When running you can get: