powershelltestingpesterpester-5

Passing parameter to Pester -testcases


I am trying to figure out the best way to parameterise my Pester (V 5.3.3) testcases. The scenario is this. I would like to check that a list of logins exist on a group of database instances. My code is pretty repetitive, and looks like this:

Describe 'Check that logins exist' {

    It "Check that <value> exists on <dbInstance>" -Tag "DEV" -TestCases @(
        @{ Value = "login1"; dbInstance = 'dev01'}
        @{ Value = "login2"; dbInstance = 'dev01'}
        @{ Value = "login3"; dbInstance = 'dev01'}
    ) {
        $login = Get-DbaLogin -sqlinstance $dbInstance -SqlCredential $cred -Login $Value
        $login | Should -not -BeNullOrEmpty
    }


    It "Check that <value> exists on <dbInstance>" -Tag "SIT" -TestCases @(
        @{ Value = "login1"; dbInstance = 'sit01'}
        @{ Value = "login2"; dbInstance = 'sit01'}
        @{ Value = "login3"; dbInstance = 'sit01'}
    ) {
        $login = Get-DbaLogin -sqlinstance $dbInstance -SqlCredential $cred -Login $Value
        $login | Should -not -BeNullOrEmpty
    }

}

What I'd like to do is to parameterise that dbInstance value. That way, my code would look more like this:

Describe 'Check that logins exist' {

    It "Check that <value> exists on <dbInstance>" -Tag "DEV" -TestCases @(
        @{ Value = "login1"; dbInstance = #dbInstance#}
        @{ Value = "login2"; dbInstance = #dbInstance#}
        @{ Value = "login3"; dbInstance = #dbInstance#}
    ) {
        $login = Get-DbaLogin -sqlinstance $dbInstance -SqlCredential $cred -Login $Value
        $login | Should -not -BeNullOrEmpty
    }

}

Then when I run my test, I'd like to pass multiple values to #dbInstance#, and then I'd like the code to run once per value passed to #dbInstance#. That way it doesn't matter how many database instances I need to run it against, and I'm keeping code repetition to a minimum. Hopefully that makes sense. Anyone got any good ideas, or examples I could follow? Thanks a lot!


Solution

  • If I understand your intent correctly, wrapping your test in a ForEach-Object pipeline as follows may work:

    Describe 'Check that logins exist' {
    
      # Provide the names of the DB instances as input.
      'dev01', 'sit01' |
        ForEach-Object {
    
          $tag = $_.Substring(0, 3).ToUpper() # derive the -Tag value
    
          # Note the use of $_ in the hashtables to refer to the instance at hand.
          It "Check that <value> exists on <dbInstance>" -Tag $tag -TestCases @(
            @{ Value = "login1"; dbInstance = $_ }
            @{ Value = "login2"; dbInstance = $_ }
            @{ Value = "login3"; dbInstance = $_ }  
          ) {
            $login = Get-DbaLogin -sqlinstance $dbInstance -SqlCredential $cred -Login $Value
            $login | Should -not -BeNullOrEmpty
          }
    
        }
     
    }