Thursday, July 26, 2007

Fixture path in ActiveRecord Testing

I am using fixture in ActiveRecord Testing. I have many test classes, each using fixtures located in different directories. Individual test work fine, but fails when running together in suite. The problem is fixture_path is class attribute/variable of Test::Unit::TestCase so all subclasses of it share the same value.
require 'rubygems'
require 'active_record'
require 'active_record/fixtures'

class TestFoo < Test::Unit::TestCase
   self.fixture_path='/u01/test/fixtures/foo'
end

TestFoo.fixture_path # "/u01/test/fixtures/foo"

class TestBar < Test::Unit::TestCase
   self.fixture_path='/u01/test/fixtures/bar'
end

TestBar.new().fixture_path # "/u01/test/fixtures/bar"
TestFoo.new().fixture_path # "/u01/test/fixtures/bar"
Because the Test Unit framework, load all test classes, then run them, so TestFoo.new().fixture_path get value of TestBar.new().fixture_path. The solution is simple, just define a method fixture_path in each test class (in upcoming version after ActiveRecord 1.15.3, the problem is fixed by change fixture_path to class instance variable see ticket 6672).
class TestFoo < Test::Unit::TestCase
   def fixture_path
      '/u01/test/fixtures/foo'
   end
end

class TestBar < Test::Unit::TestCase
   def fixture_path
      '/u01/test/fixtures/bar'
   end
end

TestBar.new().fixture_path # "/u01/test/fixtures/bar"
TestFoo.new().fixture_path # "/u01/test/fixtures/foo"

No comments: