Ruby on Rails With No Database

Dec 21, 2011 Published by Tony Primerano

Rails Recipes has a recipe for running your rails application without a database. I was building a rails app that consumed a web service so this recipe was perfect for what I was doing. I had to make a few tweaks for it to work so I figured I would document them here.

Rather than repeat my application here I'm just going to build a simple proxy in rails.

Lets build a simple rails app and add a controller.

  • rails nodb
  • script/generate controller proxy
  • edit app/controllers/proxy_controller.rb
class ProxyController < ApplicationController
  def get
    url = URI.parse(params["url"])
    result = Net::HTTP.get_response(url)
        #render error if result. ...
        render :text => result.body

Now there is obviously no need for a database in this application but if we try to run tests we'll see how rails is hard wired to expect a database.

run rake test and watch it fail.. unless of course you have a nodb_development database setup. Running rake with the -P shows that there is a db:test:prepare prerequisite task. Chads book goes into more details but the solution is as follows. remove the test_help require from test_helper.rb and steal the requires from test_help.rb (except the active record require). Buy Rails Recipies. it rocks.

Code and Details are here

I kept the Test::Unit::TestCase class and just commented out these lines

  • # self.use_transactional_fixtures = true
  • # self.use_instantiated_fixtures = false

I did this because I added helper methods later.

The final item to make the rake task work is to create the following file lib/tasks/clear_database_prerequisites.rake

Some of the symbols in the book did not work for me so I used the string literals (you can find them via rake -T

Here is what I ended up using

["test:units", "test:functionals", "test:integration", :recent].each do |name|

In addition to not needed a database my application had no need for sessions either. So rather than deal with cookie passing and session cleanup I edited my application.rb file to turn off session.

# session :session_key => '_nodb_session_id'
session :off

Now that we have a database and session free application how exactly do we test it? Some of the testing power of rails is lost when you are talking to a service but I'll walk you through how I tested my database less models next

Testing Ruby on Rails Models with no Database Mapping