Skip to content

Instantly share code, notes, and snippets.

@teklakct
Last active May 15, 2017 18:26
Show Gist options
  • Save teklakct/634db3b13e250ec4dba6 to your computer and use it in GitHub Desktop.
Save teklakct/634db3b13e250ec4dba6 to your computer and use it in GitHub Desktop.
Symfony 2.5 profiler a Behat 3
imports:
- { resource: config_dev.yml }
framework:
test: ~
session:
storage_id: session.storage.mock_file
profiler:
enabled: true
collect: false
only_exceptions: false
web_profiler:
toolbar: false
intercept_redirects: false
swiftmailer:
disable_delivery: true
default:
suites:
default:
contexts:
- FeatureContext:
profiler: '@profiler'
filters:
tags: "~@javascript"
extensions:
Behat\MinkExtension:
base_url: 'https://example.dev/app_test.php/'
sessions:
default:
symfony2: ~
javascript:
selenium2:
wd_host: http://33.33.33.1:4444/wd/hub
browser_name: chrome
show_auto: false
Behat\Symfony2Extension: ~
<?php
namespace Bundle\WebsiteBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouterInterface;
/**
* @Route(service="bundle.controller.Default")
*/
class DefaultController
{
/**
* @var \Symfony\Component\Form\FormFactoryInterface
*/
private $formFactory;
/**
* @var \Swift_Mailer
*/
private $mailer;
/**
* @var \Symfony\Component\Routing\RouterInterface
*/
private $router;
public function __construct(FormFactoryInterface $formFactory, \Swift_Mailer $mailer, RouterInterface $router)
{
$this->formFactory = $formFactory;
$this->mailer = $mailer;
$this->router = $router;
}
/**
* @Route("/somePath")
* @Template()
*/
public function showAction(Request $request)
{
$form = $this->formFactory->create('formServiceName');
if ($request->getMethod() === 'POST') {
$form->submit($request);
if ($form->isValid()) {
$message = \Swift_Message::newInstance()
->setSubject('Mail Subject')
->setFrom('send@example.com')
->setTo('receive@example.com')
->setBody('Lorem Ipsum')
;
$this->mailer->send($message);
$request->getSession()->getFlashBag()->add('success','Well donea');
} else {
$request->getSession()->getFlashBag()->add('error','Something went wrong');
}
}
return array(
'form' => $form->createView(),
);
}
}
<?php
use Behat\Behat\Context\SnippetAcceptingContext;
use Behat\MinkExtension\Context\MinkContext;
use Symfony\Component\HttpKernel\Profiler\Profiler;
class FeatureContext extends MinkContext implements SnippetAcceptingContext
{
/** @var \Symfony\Component\HttpKernel\Profiler\Profiler */
private $profiler;
public function __construct(Profiler $profiler)
{
$this->profiler = $profiler;
$this->profiler->enable();
}
/**
* @BeforeScenario
*/
public function enableFollowRedirects()
{
$this->getClient()->followRedirects(true);
}
/**
* @When I press :button without redirection
*/
public function iPressWithoutRedirection($button)
{
$this->getClient()->followRedirects(false);
$button = $this->fixStepArgument($button);
$this->getSession()->getPage()->pressButton($button);
}
/**
* @When /^I follow the redirection$/
* @Then /^I should be redirected$/
*/
public function iFollowTheRedirection()
{
$client = $this->getClient();
$client->followRedirects(true);
return $client->followRedirect();
}
/**
* @Then /^no email should have been sent$/
*/
public function noEmailShouldHaveBeenSent()
{
/** @var Symfony\Bundle\SwiftmailerBundle\DataCollector\MessageDataCollector $mailer */
$mailer = $this->getProfiler()->getCollector('swiftmailer');
if (0 < $count = $mailer->getMessageCount()) {
throw new \RuntimeException(sprintf('Expected no email to be sent, but %d emails were sent.', $count));
}
}
/**
* @Then email with subject :subject should have been sent to :to
*/
public function emailWithSubjectShouldHaveBeenSentToWith($subject, $to)
{
/** @var Symfony\Bundle\SwiftmailerBundle\DataCollector\MessageDataCollector $mailer */
$mailer = $this->getProfiler()->getCollector('swiftmailer');
if (0 === $mailer->getMessageCount()) {
throw new \RuntimeException('No emails have been sent.');
}
$foundToAddresses = null;
$foundSubjects = array();
foreach ($mailer->getMessages() as $message) {
$foundSubjects[] = $message->getSubject();
$foundToAddresses = implode(', ', array_keys($message->getTo()));
if (trim($subject) === trim($message->getSubject())) {
return;
} else {
continue;
}
}
if (!$foundToAddresses) {
if (!empty($foundSubjects)) {
throw new \RuntimeException(sprintf('Subject "%s" was not found, but only these subjects: "%s"', $subject, implode('", "', $foundSubjects)));
}
// not found
throw new \RuntimeException(sprintf('No message with subject "%s" found.', $subject));
}
throw new \RuntimeException(sprintf('Subject found, but "%s" is not among to-addresses: %s', $to, $foundToAddresses));
}
/**
* @return Symfony\Bundle\FrameworkBundle\Client
*/
private function getClient()
{
return $this->getSession()->getDriver()->getClient();
}
/**
* @return \Symfony\Component\HttpKernel\Profiler\Profile
*/
private function getProfiler()
{
return $this->getClient()->getProfile();
}
}
@teklakct
Copy link
Author

Mój problem polega na tym, że w takiej w tym przypadku gdy uruchomię scenariusz behata:

  Scenario: Successfully send email
    Given I am on "/somePath"
    When I fill in "Name" with "Robert C. Martin's"
    And I press "Send" without redirection
    Then email with subject "Mail Subject" should have been sent to "receive@example.com"

To profiler nie istnieje i w feature\bootstrap\FeatureContext.php:107 dostaje Try to getProfile() on non-object

W przypadku, gdy w config_test.yml zmienię parametr profilera collect na true

framework:
    ....
    profiler:
        ...
        collect: true

wszystko jest w porządku.


I teraz o co chodzi.

Profiler nie jest mi potrzebny do wszystkich scenariuszy albo nawet całych suitów (bo spowalnia całe działanie itp.). Tak też w konfiguracji dla środowiska testowego chce go mieć wyłączonego, albo przynajmniej wyłączone zbieranie danych. Dokumentacji mówi, że możemy przeczytać:
If you want to only collect information on-demand, you can set the collect flag to false and activate the data collectors by hand:

$profiler->enable();

co teoretycznie robię konstruktorze, ale to nie chcę ze mną współpracować.

Co robię źle? Jakieś pomysły?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment