Using fixtures to provide initial data

Fixtures are the Swiss Army knife of database independent seed data. By defining and describing your data entities in a text file it is pretty simple to load it into an arbitrary database.

This serves two purposes. First, you can make sure in your tests, that certain data exists when running the tests. Second, you can ensure that the must-have data like a first administrative account in your application exists, when deploying and starting your application in production.

How to do it...

Define a fixtures file and store it under conf/initial-data.yml:

User(alr):
        login: alr
        password: test
        email: [email protected]

Tweet(t1):
        content: Lets get ready to tweet
        postedAt: 2010-11-22T08:23:15
        login: alr

How it works...

As you can see in the preceding snippet, there are two entities defined. The first one only consists of strings, whereas the second one consists of a date and a reference to the first one, which uses the name in parentheses after the type as a reference.

There's more...

Fixtures are helpful in two cases. For one you can ensure the same test data in your unit, functional, and selenium tests. Also you can make sure, that your application is initialized with a certain set of data, when the application is loaded for the first time.

Using a bootstrap job to load seed data

If you need to initialize your application with some data, you can execute a job loading this data at application startup with the following code snippet:

@OnApplicationStart
public class Bootstrap extends Job {

    public void doJob() {
        // Check if the database is empty
        if(User.count() == 0) {
          Fixtures.load("initial-data.yml");
        }
    }

You should put the referenced initial-data.yml file into the./conf directory of your application. If you reference it with its filename only in any class like in the doJob() method that we saw some time back, it will be found and loaded in your current database by using the count() method of the User entity. Also by extending this class from Job and putting the @OnApplicationStart annotation at the top, the doJob() method is executed right at the start of the application.

More information about YAML

Play uses SnakeYAML as an internal YAML parser. You can find out more about the integration at either http://www.playframework.org/documentation/1.2/yaml or http://code.google.com/p/snakeyaml/.

Using lists in YAML

Fixtures are quite flexible, they also allow lists; for example, if the tags field is from type List<Tag>, this works:

tags:             [tag1, tag2, tag3, tag4]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.36.194