Behat is not only for BDD
What is Behat?
Behat is an open source Behavior-Driven Development framework for PHP.
In few words, It helps us to write end-to-end tests with gherkin each line of gherkin is a step and each step corresponds to a PHP function executed to assert or execute the statement.
Example of end-to-end test with behat :
Our use case, test the PUT operation of an API
The test could be like :
To be honest, I’m not a big fan of functional tests with PHPUnit, I found them “ugly” and some of them can be difficult to read so I prefer to hijack Behat of its first purpose (BDD testing) and write functional tests in Gherkin to make them more readable and that’s why for me Behat is not only for BDD.
Let’s see the same test in Gherkin :
It’s a matter of taste but I prefer the second and there are many advantages to this test :
- Readability (Cool for front devs who understand nothing about PHP)
- API Documentation and sample
- Fast to write
- Closer to API consumption (Json Payload)
You can also test error scenario :
I have worked with some developers who are not used to writing tests with this approach, it seems simple to them and they enjoy writing tests ❤️
Let’s see other use cases of functional tests with Behat:
Messenger and Elasticsearch
Test that dispatches a message in a specific queue with Messenger will update a document in Elasticsearch
Export a CSV via Mail and check the content
Test a Command that creates an Oauth Client
💡Behind each step, we have a Context file written in PHP that will execute the statement or make the assertion.
You can imagine any step, check a value in a database, check the content of PDF, check the content of a queue, count the number of messages inside a queue… The limit is your imagination ☁️
You can create any step that will be in adequacy with the real utilization and that’s the purpose of writing tests, be able to refactor and check that the code did the job ✔️
PHPUnit or Behat are just tools, it’s up to you to choose which feet your need but with PHPUnit, this kind of test can be very painful, the only difficult part from Behat is to write the step in the context file that will do the job (execute a statement or make an assertion) but you have to do it once and then any developer can reuse the step 🔥
If you’re curious you can find examples of feature and Context in this repository