Behat and Uploading Files to a Form Even on Remote Selenium2 Servers

Posted: 2016-04-27 02:52:13

Just had to tackle this issue so making some notes for later here :)

Updated and more detailed here

I run selenium on my Windows PC and before that my Mac, either one would have had this issue since my test is running side my VM. This meant when I needed to run a test to interact with a form to upload an image that image path was relative to the machine (VM) that I started the test on and not the Browser that was being manipulated by Selenium2.

The solution was "easy" thanks to this thread

After that my step just looked like this and I was done

    /**
     * @Then I should be able to upload an image file
     */
    public function iShouldBeAbleToUploadAnImageFile()
    {
        $localFile = base_path('features/assets/profile.jpg');
        $tempZip = tempnam('', 'WebDriverZip');
        $zip = new \ZipArchive();
        $zip->open($tempZip, \ZipArchive::CREATE);
        $zip->addFile($localFile, basename($localFile));
        $zip->close();

        $remotePath = $this->getSession()->getDriver()->getWebDriverSession()->file([
            'file' => base64_encode(file_get_contents($tempZip))
        ]);

        $this->attachFileToField('profile_image', $remotePath);

        unlink($tempZip);

        $this->pressButton('Save');
    }

I also had to add @javascript to the test to allow this WebDriver feature to work.

That was it, saved me a ton of time suffering through this gotcha moment.