Behat Attachment File does not work

6.6k Views Asked by At

I am using ‘selenium2’ driver and trying to test the file upload form input field but getting error as

Exception thrown by (//html/descendant-or-self::*[@id = 'ImageID'])[1]
'D:/looks.jpg' does not exist on the file system

My code In FeatureContex.php as bellow

>     $page = $this->getSession()->getPage();
>     $element = $page->find('css', '#ImageID');
>     $element->attachFile('D:/looks.jpg');
4

There are 4 best solutions below

2
On

Here, this code is the default code of behat and mink. try this.

/**
 * Attaches file to field with specified id|name|label|value.
 *
 * @When /^(?:|I )attach the file "(?P<path>[^"]*)" to "(?P<field>(?:[^"]|\\")*)"$/
 */
public function attachFileToField($field, $path)
{
    $field = $this->fixStepArgument($field);

    if ($this->getMinkParameter('files_path')) {
        $fullPath = rtrim(realpath($this->getMinkParameter('files_path')), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$path;
        if (is_file($fullPath)) {
            $path = $fullPath;
        }
    }

    $this->getSession()->getPage()->attachFileToField($field, $path);
}
0
On

This is a very simple reason why your code might not work, but you have the directory slash the wrong way round. The use of D: indicates windows, and the slash you have used is the / (*nix, mac, etc)...

So try replacing

    $element->attachFile('D:/looks.jpg');

with

    $element->attachFile('D:\looks.jpg');
0
On

Try using %paths.base% before specifying your folder. In my case I called it "media" and it is located in the feature folder.

default:
  extensions:
    Behat\MinkExtension:
      files_path: "%paths.base%/media/"

From the feature I specify the file name i.e.

When I add cover art "wrongCoverArt.jpg"

And receiving the file name like this:

class TypeMeContext extends RawMinkContext implements Context, SnippetAcceptingContext
...
/**
 * @When I add cover art :arg1
 */
public function iAddCoverArt($arg1)
{
    $this->uploader->addCoverArt($arg1);
}

and

class Whatever extends Page
...
/**
 * @param string $fileName
 */
public function addCoverArt($fileName)
{
    $id = 'cover-art-uploader';
    $this->attachFileToField($id, $fileName);
}
1
On

Did you define files_path? Mine is in behat.yml. If you have defined this you'd only provide the filename which should exist in the folder defined.

  default:
    context:
      class:  'FeatureContext'
    extensions:
      Behat\MinkExtension\Extension:
        files_path: '/var/www/project/public/images'
        base_url:  'https://local.dev'