6

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?

Adam
  • 3,891
  • 3
  • 19
  • 42
  • 1
    try `return $using:var`? – 4c74356b41 Apr 05 '18 at 20:36
  • 1
    Any issues using scope with pester? `$script:var = 1` or `$global:var = 1` – G42 Apr 05 '18 at 20:40
  • 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 Apr 05 '18 at 20:42
  • 1
    @gms0ulman, those worked! I swear I tried $global before posting this, but trying them both now did the trick. – Adam Apr 05 '18 at 20:44

2 Answers2

4

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
}
wekempf
  • 2,738
  • 15
  • 16
  • GetNewClosure() is a better option than global scope and I am not sure it is documented in Pester - https://github.com/pester/Pester/issues/204, there is also InModuleScope if you want to access variables and private functions from module you are testing - https://github.com/pester/Pester/wiki/InModuleScope – severian May 06 '19 at 13:39
0

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.

G42
  • 9,791
  • 2
  • 19
  • 34