Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

94 | Chapter 3: Rails Plugins


To make this work, a set of test model objects and corresponding fixtures are
included in the plugin’stest/fixturesdirectory. The plugin also includes a database
schema backing the models (schema.rb) and some statements intest_helper.rbthat
load the fixtures into the database. The full test directory structure is shown in
Figure 3-2.


The first piece of the puzzle is thedatabase.ymlfile, which includes not only configu-
ration blocks for standard DBMSs, but also for SQLite and SQLite3, which save their
database in a local file:


sqlite:
:adapter: sqlite
:dbfile: state_machine.sqlite.db
sqlite3:
:adapter: sqlite3
:dbfile: state_machine.sqlite3.db
# (postgresql and mysql elided)

The schema files, fixtures, and models are self-explanatory; they are a Ruby schema
file, YAML fixtures, and ActiveRecord model classes, respectively. The real magic
happens intest_helper.rb, which ties everything together.


The test helper first sets up Rails load paths and loads ActiveRecord. Then it loads
database.ymland instructs ActiveRecord to connect to the database (defaulting to
SQLite):


config = YAML::load(IO.read(File.dirname(_ _FILE_ _) + '/database.yml'))
ActiveRecord::Base.logger = Logger.new(File.dirname(_ _FILE_ _) + "/debug.log")
ActiveRecord::Base.establish_connection(config[ENV['DB'] || 'sqlite'])

Next, the schema file is loaded into the database:


load(File.dirname(_ _FILE_ _) + "/schema.rb") if
File.exist?(File.dirname(_ _FILE_ _) + "/schema.rb")

Finally, the plugin’s fixture path is set asTestCase’s fixture path and added to the
load path so that models in that directory will be recognized:


Test::Unit::TestCase.fixture_path = File.dirname(_ _FILE_ _) + "/fixtures/"
$LOAD_PATH.unshift(Test::Unit::TestCase.fixture_path)

Figure 3-2. Plugin testing directory structure

Free download pdf