Aşağıdaki örnekte, içinde dosya eklentisi olan bir API isteğini test edeceğiz. Buradaki kritik nokta, FeatureContext dosyasındaki I attach files to my request adımıdır.


Upload klasörü


Uygulamanızda src/Application/FrontendBundle/Resources/upload/.gitkeep klasörünü yaratın.


Parameters.yml


parameters:
upload_dir: %kernel.root_dir%/../src/Application/FrontendBundle/Resources/upload/

Behat senaryosu


Bu senaryo olmayan test dosyalarını yaratır, API isteğine ekler ve isteği adrese gönderir.


Feature: Uploading files as part of request
In order to upload files
As a user
I should be able to send a request that contains message body and files

Scenario: I can send request with files attached to it
Given there are dummy files to test
And I attach files to my request
Then I send "POST" request to "/message" with body:
"""
{
"body": "I also have attachments in this request"
}
"""

FeatureContext


namespace Application\FrontendBundle\Features\Context;

use Behat\Gherkin\Node\PyStringNode;
use Behat\MinkExtension\Context\MinkContext;
use Behat\Symfony2Extension\Context\KernelAwareContext;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpKernel\KernelInterface;

class FeatureContext extends MinkContext implements KernelAwareContext
{
const DUMMY_FILE_PNG = 'dummy.png';
const DUMMY_FILE_DOC = 'dummy.doc';

private $attachments;

/** @var KernelInterface */
private $kernel;

public function setKernel(KernelInterface $kernelInterface)
{
$this->kernel = $kernelInterface;
}

/**
* @Given /^there are dummy files to test$/
*/
public function thereAreDummyFilesToTest()
{
file_put_contents($this->getCacheTestDir().self::DUMMY_FILE_PNG, 'PNG');
file_put_contents($this->getCacheTestDir().self::DUMMY_FILE_DOC, 'DOC');
}

/**
* @Then /^I attach files to my request$/
*/
public function iAttachFilesToMyRequest()
{
$this->attachments[] = new UploadedFile(
$this->getCacheTestDir().self::DUMMY_FILE_PNG,
self::DUMMY_FILE_PNG,
'image/png',
3
);
$this->attachments[] = new UploadedFile(
$this->getCacheTestDir().self::DUMMY_FILE_DOC,
self::DUMMY_FILE_DOC,
'application/msword',
3
);
}

/**
* @param string $method
* @param string $url
* @param PyStringNode $data
*
* @Then /^I send "([^"]*)" request to "([^"]*)" with body:$/
*/
public function iSendRequestWithBody($method, $url, PyStringNode $data)
{
/** @var Client $client */
$client = $this->getSession()->getDriver()->getClient();
$client->request($method, $url, [], $this->attachments, [], $data);
}

/**
* @return string
*/
private function getCacheTestDir()
{
return $this->kernel->getCacheDir().'/';
}
}