Roshan Book

My Tech Notebook

Category Archives: rails

How To Get Rails 3 and RSpec 2 Running Specs Fast (From Scratch)

This post was originally published at

Rails 3 is great. RSpec 2 is great. And Ruby 1.9.2 is really great. Getting them all running together and quickly, however, isn’t entirely straightforward. In this post I demonstrate how to get everything ticking over along with automatically running, super-snappy test runs.


The ultimate outcome is using Ruby 1.9.2 (though much of this is relevant to 1.8 still) to create a Rails 3 app, hook up RSpec 2, and be able to run specs quickly. The first two parts are easy(ish) but the “quickly” part requires some tinkering. Grab a coffee and carry on..


Create a new Rails 3 app


Got Rails 3 installed? If not, gem install rails will see you good. Then head on down to your favorite project folder with your shell and create a new Rails 3 app like so:


rails new myapp --skip-test-unit


You can retroactively bring RSpec 2 into an existing Rails 3 project, of course, but it’s easier for this walkthrough to start afresh in case of application-specific issues.


Hooking up RSpec 2 with RSpec-Rails


Edit the Gemfile file in your new Rails project (myapp/Gemfile in this example) and add the following block to the bottom:


group :development, :test do
  gem 'rspec-rails'


This tells Bundler (a gem management and dependency tool Rails 3 likes to lean on) we want to use the rspec-rails gem which will get RSpec running with Rails 3.0 for us. Next, we get Bundler to do its thing:




This will install all of the gems referenced in Gemfile, including rspec-rails. (You can use bundle install instead, if you prefer, but bundle on its own works too.)


Last but not least, we need to run RSpec’s ‘generator’ that rspec-rails has put in place for us:


rails generate rspec:install


The generator creates a few files. Namely:


  • .rspec – a config file where we can store extra command line options for the rspeccommand line tool. By default it contains --colour which turns on colored output from RSpec.
  • spec – a directory that will store all of the various model, controller, view, acceptance and other specs for your app
  • spec/spec_helper.rb – a file that’s loaded by every spec (not in any automatic way but most have require 'spec_helper' at the top). It sets the test environment, contains app level RSpec configuration items, loads support files, and more.


We still can’t run rake and see anything interesting yet because we don’t have a database or any models initialized.


Creating a model to test


Let’s take the easy way out and use the scaffold generator to flesh out something for us to test (as well as to see what spec files can be generated automatically):


rails generate scaffold Person name:string age:integer zipcode:string


It’s worth noting that when you generate the scaffold numerous spec files are also created (thanks to rspec-rails):




Now bring the database up to speed with the migration for the new model:


rake db:migrate


Now let’s run rake – finally! The result:



  PeopleHelper add some examples to (or delete) /Users/peter/dev/rails/myapp/spec/helpers/people_helper_spec.rb
    # Not Yet Implemented
    # ./spec/helpers/people_helper_spec.rb:14
  Person add some examples to (or delete) /Users/peter/dev/rails/myapp/spec/models/person_spec.rb
    # Not Yet Implemented
    # ./spec/models/person_spec.rb:4

Finished in 0.31043 seconds
29 examples, 0 failures, 2 pending


Rock and roll. We’re up and running. Sort of. Let’s put in some “real” specs to be sure things are working nicely.


Change spec/models/person_spec.rb to the following rather contrived pair of specs:


require 'spec_helper'

describe Person do
  it "can be instantiated" do be_an_instance_of(Person)

  it "can be saved successfully" do
    Person.create.should be_persisted


Not the most useful things to spec out, admittedly, but you get a little database action and get rid of a pending spec we had cluttering things up. We haven’t got anything else we can seriously test yet anyway.


Now let’s run rake spec:models to focus our efforts on what we’ve just done:



Finished in 0.09378 seconds
2 examples, 0 failures


How to have specs run automatically with Watchr


Let’s assume we’ve progressed with developing our app and we’re working on models and controllers, testing along the way. Rather than running rake or bundle exec rspec all of the time, wouldn’t it be great to have the relevant spec run automatically when we either edit the spec or a model/controller that has a spec? Well, with watchr, we can. (Note: Some people prefer autotest. I find watchr more flexible and useful for other things beyond just running specs.)


But if you really want to use autotest, Mike Bethany explains how to set it up in a similar scenario in a post of his own, along with autotest-growl for OS X notifications.


Add watchr to your Gemfile‘s testing and production gem section:


group :development, :test do
  gem 'rspec-rails'
  gem 'watchr'


Then run bundle to install it.


Next, create a file called .watchr in your app’s root folder and populate it with this code:


def run_spec(file)
  unless File.exist?(file)
    puts "#{file} does not exist"

  puts "Running #{file}"
  system "bundle exec rspec #{file}"

watch("spec/.*/*_spec.rb") do |match|
  run_spec match[0]

watch("app/(.*/.*).rb") do |match|
  run_spec %{spec/#{match[1]}_spec.rb}


This ‘watchr script’ directs a running watchr process to do a few things:


  • If any file ending in _spec.rb under the spec/ directory changes, run therun_spec method with its filename.
  • If any .rb file under the app/ directory changes, call the run_spec method with an equivalently named _spec.rb file under spec.
  • run_file accepts a filename for a spec file, checks it exists, and tells the system to run it (using system)


If you now run watchr .watchr to use the .watchr script, not much will happen. But if you make any change (or even just re-save) to, say, spec/models/person_spec.rb, that spec will run automatically. Make a change to app/models/person.rb and it’s the same deal. To stop watchr, CTRL+C saves the day.


Watchr can be used for a lot more than this but this is just for starters 😉


Optionally, you might also like to create lib/tasks/watchr.rake and include the following code so you can just remember to run rake watchr instead (it’s nice to have anything you run within a project contained in one place):


desc "Run watchr"
task :watchr do
  sh %{bundle exec watchr .watchr}


How to get faster spec runs with Spork


We’ve got Rails 3 running with RSpec 2 and watchr’s giving us some automatically-running-spec love. But do you notice how slow it is? Specs run quickly once they’re loaded but there are several seconds of waiting beforehand.


If you run time rake spec:models with Ruby 1.9.2, you’ll probably see a wallclock time of over 5 seconds (5.204s on my machine and I’m SSDed up) – holy splingledoops! If not, you’re lucky, but it’s a commonly reported problem with some improvements expected in Ruby 1.9.3. We can’t wait that long though..


Enter Spork. Spork is a tool that loads the Rails environment and then forks each time you want to run some specs (or tests, it can be set up to run with Test::Unit too). In this way, the whole Rails initialization process is skipped, shaving valuable seconds off of your spec runs.


Edit your Gemfile again and include Spork:


gem 'spork', '~> 0.9.0.rc'


Run bundle to install Spork.


Next, Spork needs to make some changes to yourspec/spec_helper.rb file. Because it only initializes the Rails environment once and then forks it, you might have initialization features that you need to run on each test run. Spork will let you do this but it needs to make those changes first. Run:


spork --bootstrap


The result:


Using RSpec
Bootstrapping /Users/peter/dev/rails/myapp/spec/spec_helper.rb.
Done. Edit /Users/peter/dev/rails/myapp/spec/spec_helper.rb now with your favorite text editor and follow the instructions.


Bring up spec/spec_helper.rb. All spork --bootstrap has done is add some extra code to the top of the file. Read the comments there to get a better feel for what to do and what Spork requires and keep them in mind as we progress (in case you want to do something differently).


Get rid of require 'rubygems' from the first line – we’re using Bundler so it’s not necessary.


Next, cut and paste all of the ‘old’ contents of spec_helper.rb into the Spork.preforkblock. Since we’re running an empty(ish) project, there’s nothing special we’ve added that we need to run on each run using the Spork.each_run block. We can leave that empty.


You’ll end up with a spec_helper.rb file that looks like this:


require 'spork'

Spork.prefork do
  # Loading more in this block will cause your tests to run faster. However, 
  # if you change any configuration or code from libraries loaded here, you'll
  # need to restart spork for it take effect.
  # This file is copied to spec/ when you run 'rails generate rspec:install'
  ENV["RAILS_ENV"] ||= 'test'
  require File.expand_path("../../config/environment", __FILE__)
  require 'rspec/rails'

  # Requires supporting ruby files with custom matchers and macros, etc,
  # in spec/support/ and its subdirectories.
  Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

  RSpec.configure do |config|
    # == Mock Framework
    # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
    # config.mock_with :mocha
    # config.mock_with :flexmock
    # config.mock_with :rr
    config.mock_with :rspec

    # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
    config.fixture_path = "#{::Rails.root}/spec/fixtures"

    # If you're not using ActiveRecord, or you'd prefer not to run each of your
    # examples within a transaction, remove the following line or assign false
    # instead of true.
    config.use_transactional_fixtures = true

Spork.each_run do
  # This code will be run each time you run your specs.


Head back to your shell and the root of your project and run spork:


Using RSpec
Loading Spork.prefork block...
Spork is ready and listening on 8989!


Now we’re cooking with gas. Open another shell, head to the root of your project, and runwatchr .watchr too. Then head to spec/models/person_spec.rb in your text editor and re-save it (or even make a change if you want). Your specs run but.. they’re no faster! What’s wrong?


It turns out we need to make another change so that RSpec knows we’re running Spork. Edit the .rspec file (mentioned earlier) and add --drb to the line (so it probably reads --colour --drb). Now, edit the spec again, save, and.. fast!


You should note that if you use rake at this point to run your entire suite, it’ll still not be particularly fast because rake itself is initializing Rails in order to do its job. But if you want to run your entire suite quickly, just run:


rspec spec


With our dummy app and on my machine, this runs in a wallclock time of 0.759s – a serious improvement over 5.2 seconds.


We have Rails 3, RSpec 2, watchr, spork, and SUPER-DUPER FAST SPECS all running on Ruby 1.9.2. Score!


A minor snafu will remain, though. If you update app/models/person.rb, the change won’t take effect in your tests since Spork has the old Person still in memory. One way around this is to edit config/environments/test.rb and change:


config.cache_classes = true




config.cache_classes = false


Now your app’s classes are reloaded when necessary.






Installing Ruby on Rails Ubuntu 11.10 using RVM and Ruby 1.9.2

This post was originally published at

Ruby Rails is a Web application framework created in 2004 intended as a rapid development web framework that runs the Ruby programing language. The latest version of the Ruby is ‘Ruby 1.9.2‘ and was realised in August 2011, it brings many new features and bug fixeses. The most signifiant changes are Block local variables, An additional lambda syntax, Per-string character encodings are supported and a new New socket API (IPv6 support). You can find a great walkthrough of all the new features at Ruby Inside. coinciding with the release of Ruby 1.9 is the Rails 3.1 framework which requires Ruby 1.8.7 or higher. RubyonRails 3.1 brings many new features, most notably: jQuery as default, HTTP Streaming, a new assets pipeline powered by Sprockets 2.0. So this is all good stuff and I’m sure you want to be working with the latest version of Ruby and RubyonRails, especially if you setting up a new server.


Well if your using Ubuntu you can setupRuby and RubyonRails quickly using the supplied repository’s, a good tutorial for this can be found here. However this is not recommended as the Ubuntu repositories are often out of date and if you install ruby orrails via the repository’s it can be pain toupgrade. So in this guide we are going to go through installing RVM (this allows you toinstall, change and upgrade the installedRuby version), Ruby 1.9.2 and Rails 3.1. This Guide has been tested on Ubuntu 11.10 however it should work on all versions of Ubuntu later then Ubuntu 9.04.

First of all you’ll need to install some packages that Ruby, RVM and RubyOnRailswill require later, the easiest way to do this is using the repositories so go to your terminal and type:

sudo apt-get update
sudo apt-get install build-essential git-core curl libmysqlclient16-dev nodejs

Now let’s install the latest version of RVM using curl:

bash < <(curl -s
echo '[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"' >> ~/.bashrc

Now you’ll need to ask RVM if it needs any more programs and if so you’ll need to install them to do this type:

rvm requirements

Two things could happen here if you see the following message saying you need to install ‘rvm‘, ignore this it and restart your terminal, this should fix the problem.

The program 'rvm' is currently not installed.  You can install it by typing:
sudo apt-get install ruby-rvm

You should see something that looks like this after you restart your terminal:

This tells you which packages you need to install using apt-get, just copy and paste the apt-get section under “# ForRuby” and run using the sudo command, this should look something like this:

sudo apt-get install build-essential openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev automake libtool bison subversion

Once you have installed all these packages its time to install Ruby 1.9.2 herself. The following command will installRuby 1.9.2 using the rmv package. However this can take a few minutes (15 in my case) to install so I recommend getting a drink, or my favourite, a pizza :lol: .

rvm install 1.9.2

Once ruby is installed you should set Ruby 1.9.2 as your default Ruby version, to do this enter:

rvm --default use 1.9.2

You can test that Ruby is installed correctly and running at version 1.9.2 by typing

ruby -v

This should output something like “ruby 1.9.2p290..” showing you that version 1.9.2p290 is installed and is now the defaultRuby version.

The nice thing about RVM is you can use it to install any version of Ruby and switch between the versions your have installed, to do this just enter “rvm install [Version Number]” then “rvm –default use [Version Number”, you can then use “rvm –default use” to change to any installed version.

Now that you have the latest version of ruby installed I’m sure you want to get the latest version of Rails installed, at the time of writing this tutorial that’s Rails 3.1. To installRails we can use GEM which is installed along with RVM and Ruby, to install the latest version of Rails just type, (this can take also take a while):

gem install rails

And that’s it you have now installed RVM, Ruby 1.9.2 and Rails 3.1 on Ubuntu 11.10 configured to use sqlite3, you can now setup your new Rails package with

rails new [project name]

Just as a final note, If you want to use MySQL instead of sqlite3 you’ll need to enter the following

sudo apt-get install mysql-server
gem install mysql2
rails new [project name] -d mysql




Creating to Deployment Rails application with scaffolding

1. rails new demo_app

2. rails generate scaffold User name:   user email  : string

3. You can destroy any generate function by firing destroy function like rails destroy user

4. create database as rake db:migrate

5. git status

6. git add .

7. git commit -m

8. rails console opens interactive console for rails app

9. heroku rake db.migrate – creates your database in heroku

Ruby on Rails resources

This list was originally published at



Rails 3.0 Release Notes – RailsGuides is an invaluable resource for all Ruby on Rails developers. The Rails 3 release notes provides a great overview the api changes and new features added to the framework. – Find out if your plugins work in Rails 3.

Having Ruby on Rails 3 My Way – A tutorial on how to setup Rails 3 with Mongoid, Haml, jQuery, and RSpec with Factory Girl.

The Rails Module – Nick Quaranto outlines some helpful methods in the Rails module.

Rails 3 I18n changes – A quick walkthrough the changes made to I18n.

Ruby on Rails 3 Screencast series – The official Ruby on Rails site screencast series by Gregg Pollack.

ActionController / Rack

Embracing REST with mind, body and soul – José Valim introduces RESTful responders within Rails 3 controllers.

Railscasts #224 Controllers in Rails 3 – Ryan shows us what’s new with Rails 3 controllers.

Render Options in Rails 3 – Yehuda goes through the rendering options available in Rails 3.

Adding Routes for tests / specs with Rails 3 – Jeff Dean outlines how to verify routes in our specs.

32 Rack Resources to Get You Started – A great collection of links to get you familiar with rack.


New ActionMailer API in Rails 3.0 – Mikel Lindsaar demonstrates how to use the new ActionMailer.

A Whole New ActionMailer – Mikel Lindsaar’s Rails Dispatch post giving a tour of the ActionMailer features.


ActiveModel: Make Any Ruby Object Feel Like ActiveRecord – Yehuda writes about the modularity of ActiveModel.

Railscasts #219 Active Model – See how to include certain ActiveModel modules to tableless models.

ActiveRelation: ActiveRecord Gets a Facelift – Carl Lerche introduces the new ActiveRecord finder api.

Active Record Query Interface – Pratik gives an overview of the changes made to the ActiveRecord query interface since Rails 2.

Bundler -The official project site for Bundler that includes extensive documentation.

Library Management Gets an Update in Rails 3 – Andre Arko gives an overview about bundler for the Rails Dispatch blog.

Railscasts #201 Bundler – A Railscasts by Ryan Bates demonstrating how to use bundler with Rails 3. screencast on Bundler – Our very first screencast from last February.


Rails 3 Internals: Railtie & Creating Plugins – Ilya Grigorik goes over Railties in Rails 3.

rails-templater – A template project which generates a greenfield Rails 3 application.

Making generators for Rails 3 with Thor – A tutorial showing you how to use the new generators and how to bundle them in a gem.


The Lowdown on Routes in Rails 3 – Rizwan Reza gives us a great summary of all the different ways to create routes in Rails 3.

Rails Routing from the Outside In – RailsGuide documentation about the new router.


Plugin Authors: Toward a Better Future – Yehuda goes through the changes for making plugins in Rails 3.

Customizing Rails Apps with Plugins – José Valim gives an overview of using responders, simple form, devise, and mail form plugins.

Devise 1.1 is out and ready to rock with Rails 3 – Outlines some new feature in Devise 1.1 including being able to authenticate a given url in the router!


Beginning Rails 3 – Cloves Carneiro Jr and Rida Al Barazi bring us a great beginner Rails 3 book with examples viewable in gists.

The Rails 3 Way – The ultimate Ruby on Rails reference by Obie Fernandez.

Rails 3 In Action – Ryan Bigg and Yehuda Katz deliver a great Rails book which teaches readers Rails by doing BDDwith Cucumber and RSpec.

Rails 3 Upgrade Handbook – Jeremy McAnally’s book gives you 120 pages of information about upgrading your Rails 2 application to version 3.

Ruby on Rails Tutorial: Learn Rails by Example – Michael Hartl’s ebook that teaches Rails step by step.

Open book –

Starting with rails development


1. Install from

2. Walkthrough

RailsInstaller 1.1.1 Demo from Engine Yard on Vimeo.

3. It will install all rails dependencies, gothub account, keys etc

4. Add the public key to your github account

Starting with rails

1. Create project : rails new appName

2. Starting the built in server – rails s

3. In cmd inside your project directory load .gitignore file by running

a) notepad .gitignore

b) A file having list of directories to be ignored is loaded up.

c) Delete all the entries and enter new entries from . They are













Starting git repository .  Visit for commands reference

Inside you app

1. git init

2. git add .

3. git status

4. git commit –m “comment”

5. git log

Untill now all the changes are inside local directory. To push into your git profile follow the following steps

6. git config –global “manish roshan”

7. git config –global

8. git remote add origin

9. git push origin master

This will publish your repository to github

Working on Branch

1. creating a branch – git checkout –b branchname

2. restore – git checkout –f

3. another way to restore – git reset –hardHEAD

4. commit all changes inside branch git commit –am “comment”

Restoring back to master file

5. Going as master- git checkout master

6. Getting branch list – git branch

7. Delete branch – git branch –D branchname

Starting a branch and merging with master

8. git checkout –b branchname

9. git mv oldfilename newfilename

10. git commit –am “comment”

11. git checkout master

12. Merging master and branch – git merge

13. check to see if everything is updated and nothing to commit-git status

14. git push


1. Create login account at

2. In your cmd run : gem install heroku

3. add public key – heroku keys:add

4. create  a project on heroku – heroku create

5. from inside your app git push heroku master

6. To rename your app : heroku rename appname

%d bloggers like this: