Fixtures are used to load a controlled set of data into a database. This data can be used for testing or could be the initial data required for the application to run smoothly. Symfony2 has no built in way to manage fixtures but Doctrine2 has a library to help you write fixtures.
The goal of this article is to give a new method based on Gherkin language and Behat 3 to write and load fixtures on Symfony2.
There are two main ways to write Symfony2 fixtures.
Write your entities directly in PHP:
Or use yml format (with hautelook/alice-bundle):
Fixtures in Gherkin language
Here, I am offering you a third way, based on Gherkin language and interpreted by Behat:
Gherkin language is more condensed and less verbose than yml format, which makes it more readable. So, even if you are not a developer, you can write it.
Translate Gherkin language to data
If you already use Behat on your project, “Given” steps should already have been defined in one of your Context.
Example of steps corresponding to fixtures above:
Behat test uses test databases, but fixtures have to use dev databases. Create behat_fixtures.yml file in the root directory of your project as shown below:
First you have to define the environment that you need: dev (default value is test):
Then, specify the folder that holds fixtures files, here src/AppBundle/DataFixtures/:
Context class list is the same as Behat test. Just add FixturesContext (see below).
Manage databases before loading fixtures
First, ensure that the database host is localhost (on a vagrant for example), in order to avoid clearing wrong databases.
Next, delete database schema, then re-create the schema from doctrine entities. You can also use a migration script like DoctrineMigration.
Fixtures format is Gherkin language, as Behat scenarios. Example:
Put your fixtures files *.feature on the folder defined in behat_fixtures.yml (here src/AppBundle/DataFixtures/).
Behat processes files in alphabetical order. If you prefix the name of fixtures with a number, you can control the execution order.
To load fixtures, execute the script below in your project root and wait a few seconds!
There are many benefits to using Behat 3 to load fixtures:
Fixtures are more readable and easy to write
If you already use Behat 3, your current steps definitions can be reused
If you add a column on one of your table, you need to modify only one piece of code to make Behat tests and fixtures evolve
In your steps definitions, you can easily define default values (example: users password could be “pwd” by default)
For me, the only negative point is that the execution time is greater than classical Symfony2 fixtures.
If you like Behat, you will love writing fixtures with it!