Symfony 3.4中如何在浏览器展示Behat特性的格式化测试结果
Absolutely! There are a couple of straightforward ways to get your Behat test results formatted nicely and accessible via a browser in your Symfony 3.4 project. Here are the most practical approaches:
1. Generate Static HTML Reports (Simplest Method)
Behat comes with a built-in HTML formatter that can generate a clean, interactive report file you can serve directly through Symfony's web server.
Step 1: Configure the HTML Formatter
Edit your behat.yml file to add the HTML formatter configuration. Add this under the formatters section (create it if it doesn't exist):
default: # ... your existing Behat config ... formatters: html: output_path: '%paths.base%/web/behat-report.html'
This tells Behat to save the HTML report in your Symfony web/ directory (the default web root for 3.4), making it accessible via your app's URL.
Step 2: Generate and Access the Report
Run your Behat tests with the HTML format flag:
bin/behat --format=html
Once the tests finish, you can view the report by visiting http://your-app-url/behat-report.html in your browser. The report includes detailed steps, pass/fail statuses, and even error traces for failed tests.
2. Create a Dynamic Endpoint to Run Tests and Show Results
If you want to trigger test runs and view results on-demand via a URL, you can build a simple Symfony controller to handle this. Important: Only do this in your development environment—never expose this in production!
Step 1: Create the Controller
Generate a new controller (or add an action to an existing dev-only controller):
// src/AppBundle/Controller/BehatReportController.php namespace AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Process\Process; class BehatReportController extends Controller { public function indexAction() { // Restrict access to dev environment only if ($this->get('kernel')->getEnvironment() !== 'dev') { throw $this->createAccessDeniedException('This endpoint is only available in development.'); } // Run Behat with HTML output $process = new Process('bin/behat --format=html'); $process->run(); // Return the HTML response return new Response($process->getOutput(), 200, [ 'Content-Type' => 'text/html' ]); } }
Step 2: Add a Route
Add a route to app/config/routing_dev.yml (so it's only available in dev):
behat_report: path: /behat-report defaults: { _controller: AppBundle:BehatReport:index }
Now you can visit http://your-app-url/behat-report to run the tests and see the results immediately in your browser.
Security Notes
- Always restrict any Behat-related endpoints to your development environment only—you don't want unauthenticated users running tests or accessing sensitive test data in production.
- For the static report, consider adding a
.htaccessrule or Symfony access control to limit who can view it if needed.
内容的提问来源于stack exchange,提问作者stefun

