Rails Unit Testing Fixtures: Scenarios

Posted by Christopher Wojno Fri, 16 May 2008 00:56:00 GMT

I hurriedly wrote an article this morning about my adaptation of fixtures I call sub-fixtures. While it seemed like a good idea in theory, it it beastly to implement in practice. It requires writing new fixtures for every unique test (if used correctly). When used incorrectly, the test names don’t describe the data configuration being tested against.

I sat down and thought about it a little longer. What I really need is a scenario. A database state poised for a particular test. Needless to say: such a scenario is not limited to a single table. That way, the scenario is describing the database state being tested against and can therefore be used logically in other tests as well.

Only one minor change is required. In the test directory, add the following code to the body of the Test::Unit::TestCase class in test_helper.rb:

    def load_scenario( scenario )
        directory = File.dirname(__FILE__)+'/fixtures/scenarios/'+scenario+'/'
        files = Dir.entries( directory )
        files.delete( '.' ); files.delete( '..' )
        exp = /[^\.].*\.(yml|csv)$/
        models = files.select{|f| f[exp] }
        models = models.collect{|m| m.slice(0,m.length-4).to_sym}
        Fixtures.create_fixtures( directory, models )
    end

Again, it requires a special directory structure (maybe I’ll write a scenario generator later). in the test/fixtures I added a new directory: scenarios. Within that directory are other directories containing the scenarios fixture setups. For example, if I want to create a scenario where my list of weekly cookie recipes is missing a cookie and I want to test my code to see if it finds the correct missing cookie, I simply create the following directory:

test/fixtures/scenarios/missing_cookie

And in that directory, I create the following fixture files:

  • cookies.yml
  • users.yml
  • user_cookies.yml

Note: it works for .csv files as well. Simply create the fixtures like you normally would do.

Now, in your unit test code, add the following line to the beginning of your test case method:

load_scenario( 'missing_cookie' )

Now, when your test runs, it will create the scenario in the database that you specify. It will automatically load all the fixture files in the directory.

Problems

Again, if you use normal fixtures, they will be loaded and unloaded (will make testing a little slower).

Posted in  | Tags , , ,  | no comments

Comments

(leave url/email »)

   Comment Markup Help Preview comment