2
votes

Pretend I have a function like...

function Get-Something {
  return Get-DogShit
}

...in my Pester test script...

$var = 1

Mock 'Get-Dogshit' { return $var }

it 'should return true' {
  Get-Something | should $var
}

This doesn't work, but you see what I'm trying to do here? I want to get the value from a local variable into a MOCK script block. I want to avoid hard coding the return value in the mock and the expected result in the it-block. Any ideas on how I can achieve this?

2
try return $using:var? - 4c74356b41
Any issues using scope with pester? $script:var = 1 or $global:var = 1 - G42
Sadly, no, but that was a really good idea. I get the following when I try that: "A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the script block is invoked on a remote computer." - Adam
@gms0ulman, those worked! I swear I tried $global before posting this, but trying them both now did the trick. - Adam

2 Answers

1
votes

I had this problem myself, and script scope didn't work and I didn't care to use global scope. A bit of research shows how you can use closures for this.

$var = 1

Mock 'Get-Dogshit' { return $var }.GetNewClosure()

it 'should return true' {
  Get-Something | Should be $var
}
0
votes

Wasn't sure if it would work as not messed with pester before but apparently it follows the same scope rules as standard PowerShell.

So $script:var = 1, and the brute-force $global:var = 1 if it doesn't or if you need to call it from outside the script scope.