There is many tips about how to use ActiveRecord outside of Rails but rarely about ActiveRecord testing ouside of Rails. I am working on project that use ActiveRecord ouside of Rails and need to create fixture for testing. It take me a little bit of time to figure out how to do. The source code below demonstrates the trick
require 'test/unit'
require "active_record"
require "active_record/fixtures"
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:username => "nightlybatch",
:password => "secret",
:database => "web_orders"
)
#this is because fixture verify existence of rails database configuration
ActiveRecord::Base.configurations[:test] = ActiveRecord::Base.connection
class Product < ActiveRecord::Base
end
class TestFoo < Test::Unit::TestCase
#set fixture path explicitly
self.fixture_path="c:/temp"
fixtures :products
def test_ruby_on_rails_should_exist
assert products(:ruby_on_rails)
end
end
In order to pass the test, the fixture file products.yml shall be created in directory c:/temp, and products table shall be created in MySQL database
#c:/temp/products.yml
ruby_on_rails:
id: 1
name: ruby on rails
rails_recipes:
id: 2
name: rails recipes
No comments:
Post a Comment