Single-file Rails 3.2 Application

Creating a Rails 3.2 application in a single file for testing a gem.

Update 2013/05/27: configure Rails.root for the application.

Background

Gems often provide functionality specific to Rails applications, without necessarily depending on Rails themselves. To properly test these gems, we need a Rails application using it. I often see gems like this including the entire project structure for a dummy Rails application in their spec or test folder.

In the past there have been some gems such as plugin_test_helper and combustion that reduces the number of boilerplate files you need in your dummy application. However, I recently found that even without helper gems like these, you can define your entire Rails 3.x application in a single file.

Example Rails application

I based this example off this blog post and example by Julio Cesar Ody, and adapted it slightly to work in Rails 3.2.

Below is an example I use for testing middleware. I place this file in spec/dummy/application.rb.

require'rails'require'action_controller/railtie'classDummy<Rails::Application# Set Rails.root to the same folder as this fileconfig.root=File.dirname(__FILE__)# Rails needs these keys, but they don't really have to be secret for our testsconfig.session_store:cookie_store,key:'****************************************'config.secret_token='****************************************'# Log to spec/dummy/test.logconfig.logger=Logger.new(File.expand_path('../test.log',__FILE__))# This is important, otherwise the tests will failRails.logger=config.logger# The middleware I'm testingconfig.middleware.useMyMiddleware# Our routesroutes.drawdoget'/'=>'dummy#index'get'/other'=>'dummy#other'endend# A simple controllerclassDummyController<ActionController::Basedefindexrendertext:'Home'enddefotherrendertext:'Other'endend

Using the application in tests/specs

For my tests I’m using rack/test. Using the application is as simple as requiring the application file, and telling rack/test to use the it: