Behat:Goutte / Guzzle通过cURL下载文件“警告:curl_setopt_array():3607不是有效的文件句柄资源”

Using Behat to test some behavior that involves downloading a file. Using Goutte and Guzzle to intercept the file download so I can interact with it in another step.

//Where to put the file
$tmpFile = 'download.zip';
$handle  = fopen($tmpFile, 'w');

$goutteDriver = $this->getSession()->getDriver();
$goutteClient = $goutteDriver->getClient();

/** @var \Guzzle\Http\Client $guzzleClient */
$guzzleClient = $goutteClient->getClient();
$guzzleClient->getConfig()->set('curl.options', [CURLOPT_FILE => $handle]);
$guzzleClient->setSslVerification(false);

$goutteDriver->visit($url);

fclose($handle);

It works fine, but if I run two different scenarios in a row that run this same step, I get the error:

"Warning: curl_setopt_array(): 3607 is not a valid File-Handle resource"

Edit: I tried not closing the $handle, and then every scenario after it just skips instead of running. Also tried using $guzzleClient->getConfig()->remove('curl.options'); and that caused a later step to not work.

Edit2: Example of problem:

I took out all other steps except the one that I've included the code for here, the download of the zip file.

My feature now essentially looks like this:

 Background:
   Given I am logged in as an admin

 Scenario: A
    When I click "Export All"

 Scenario: B
    When I click "Export All"

When I run it, the output looks like this:

  Background:                        
    Given I am logged in as an admin

  Scenario: A
    When I click "Export All" 

  Scenario: B

Warning: curl_setopt_array(): supplied argument is not a valid File-Handle resource in C:\wamp\www\cems2\vendor\guzzle\guzzle\src\Guzzle\Http\Curl\CurlHandle.php on line 219

Call Stack:
    0.0000     131776   1. {main}() C:\wamp\www\cems2\vendor\behat\behat\bin\behat:0
    0.0360    1699576   2. Symfony\Component\Console\Application->run() C:\wamp\www\cems2\vendor\behat\behat\bin\behat:32


When I click "Export All" (skipped)

Followed by a stack trace that I can't find any reference to any of my code in. Full stack trace is here: http://pastebin.com/Fv48gdYm

I removed the part that was setting the curl opt file, and instead just read the content of the response into the file handle.

//Where to put the file
$tmpFile = 'download.zip';
$handle  = fopen($tmpFile, 'w');

$goutteDriver = $this->getSession()->getDriver();
$goutteClient = $goutteDriver->getClient();

/** @var \Guzzle\Http\Client $guzzleClient */
$guzzleClient = $goutteClient->getClient();

//Remove this
//$guzzleClient->getConfig()->set('curl.options', [CURLOPT_FILE => $handle]);

$guzzleClient->setSslVerification(false);

$goutteDriver->visit($url);

//Add this
fwrite($handle, $goutteDriver->getContent());
fclose($handle); 

And now everything works perfectly.