In BlogPost, Rails, Ruby

Using Rails Application Templates To Easily Setup a Rails Test App

As I worked with Rails more and more, I found I wanted to easily do a quick research spike and try different things out with a dummy Rails application.

ruby on rails

I found myself spending a lot of time issuing the rails new dummy_app command a lot. In addition, I wanted to easily set up testing with FactoryGirl and RSpec.

Consequently, I wasn’t Very DRY

DRY is an acronym meaning “don’t repeat yourself.” It’s considered a good programming practice.

With each new Rails application, I found myself constantly setting up RSpec, FactoryGirl, a login system, and various other setup tasks.

Hence, I kept wasting time repeating myself with each new dummy application.

I thought about looking into Docker but…

Then I found Rails Application Templates

From the documentation, “[a]pplication templates are simple Ruby files containing DSL for adding gems/initializers etc. to your freshly created Rails project or an existing Rails project.”

The Goodies In the Rails Template API

This post will cover a few of the most useful goodies in the Rails Template API. Also, I’ll share my own personal templates at the end of this post. If you can’t wait that long, here’s a link to my templates.

Prototyping a new rails application

Suppose you have a rails template called “my_template.rb”. You can create a new application using the code below.

Now, let’s get started with the Rails Template API goodness.

Loading environment specific gems with gem_group

First of all, to load certain gems in specific environments, you can use the gem_group option below.

This lets you use rspec-rails in development and test environments on Rails.

Executing a command with the after_bundle callback

Recently, I found out about after_bundle as shown below in an example taken from the documentation.

It registers a command to be carried out after the “gems are bundled and the binstubs are generated”.

generate

Thirdly, another useful option is generate. This command runs the rails generator with the appropriate arguments.

So the equivalent of doing rails g haml:application_layout convert is shown below.

Issue a terminal command with run

If you ever wanted to remove the default test directory from your Rails application, you might find the run command useful.

It executes a command as if you were issuing it from the terminal. In this case, since I use RSpec for testing, I remove the test directory normally included with default rails testing.

Execute a command from a directory with inside

The inside command allows you to execute a command from the specified directory.

Example – My Own Templates

Finally, here is a sample file from my own repository.

Summary

In short, the Rails Application Template API can save you a lot of time. Use it to keep exploring Rails efficiently! As promised earlier, here is a link to my templates.

Recent Posts