Drupal 8 Forms and TDD, part 1: file validation
Traditionally, testing Drupal forms has mainly consisted of testing the form through the UI using functional tests. However, with the revamp of the Forms API to a fully OO paradigm, using unit tests has now become much easier.
Using TDD when writing a form requires us to think a little bit differently about our code, compared to a more traditional approach. In this example, I'll consider a form with 3 particularities :
- a CSV file upload with a custom validation callback
- a field that only appears for users with a certain permission
- a text field with a format validation
Furthermore, upon submission, we will parse the CSV file and create new entities. I'll treat this as a series of posts. In this first post, we'll look how to get set up, and how to use TDD when writing a custom file validation callback.
Links
- Part 2.
- Part 3.
- Part 4.
- The source code for the example.
- The Composer template for Drupal project used for the project structure.
- The official documentation for writing automated tests in Drupal 8.
Enjoyed this post? Grab the RSS feed or follow me on Twitter!
Found a typo ? Correct it, submit a pull-request and get credited here!