16/12/2015 - BEHAT
In example below, we're going to send an API request that has files attached to it. The critic step here is I attach files to my request
in FeatureContext file.
Create src/Application/FrontendBundle/Resources/upload/.gitkeep
folder.
parameters:
upload_dir: %kernel.root_dir%/../src/Application/FrontendBundle/Resources/upload/
What this scenario does is, it creates files on-the-fly, attaches files to the request and sends the request to the end-point.
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"
}
"""
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().'/';
}
}