Learn-a-holic Geek Notes

Human compiled Brainwork by Kornelije Sajler.

Rails App From Scratch: Create and Configure for Testing

This blog post will be one many showing how to create Todo the Rails 3 application. The first post will be creating the Rails application and setting up the testing environment.

The app will be called Just ToDo it, just as famous Nike slogan. And also Gods of DNS where good to me so the Domain justtodoit.com is free so I bought it and the final stage of this Rails posts will be deployment to VPS and pointing to the domain JustToDoIt (Currently displays my domain metaintellect).

Create application

The command to create new Rails application and omitting default testing framework Unit::Test with switch -T or longer version is --skip-test-unit

1
2
3
4
5
6
7
8
9
$ rails new JustToDoIt -T
create
create  README.rdoc
create  Rakefile
create  config.ru
create  .gitignore
create  Gemfile
create  app
...

I had capitalized JustToDoIt before, because the name is used as Ruby class and Pascal case is convention for Ruby classes.

Then rename folder to just-todo-it to be more in *nix folder naming convention:

1
$ mv JustToDoIt just-todo-it

The fun starts when the directory is changed to Rails app directory:

1
$ cd just-todo-it

Text editor

I’ll use vim as a default text editor, for TextMate use mate and for the Sublime Text 2 use subl terminal commands for editing files instead of vim.

Gemfile

First open the Gemfile, we need to add some gems that will be used in the app and also for testing:

1
$ vim Gemfile

Edit it to include this gems:

Gemfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
source 'https://rubygems.org'

gem 'rails'
gem 'bcrypt-ruby'
gem 'unicorn'
gem 'haml'
gem 'thin'
gem 'pg'

group :test, :development do
  gem 'sqlite3'
  gem 'rspec-rails'
  gem 'pry'
  gem 'factory_girl_rails'
  gem 'database_cleaner'
  gem 'awesome_print'
  gem 'capybara'
  gem 'rb-fsevent', :require => false if RUBY_PLATFORM =~ /darwin/i
  gem 'guard-rspec'
  gem 'spork'
  gem 'guard-spork'
end

group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'
  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

After changing the Gemfile run bundler to update and download entered gems:

1
$ bundle install

Main and Production Ruby Gems

  • rails - The latest one 3.2.8 for this time of writing.
  • bcrypt-ruby - Needed for password hashing.
  • unicorn - For production, it will run as Rack HTTP Server.
  • haml - My favorite View rendering engine.
  • thin - Thin as local server instead of default Webrick.
  • pg - My default database for production usage.

Test and Development Ruby Gems

  • sqlite3 - The database used for development and testing environments.
  • rspec-rails - RSpec as default testing framework.
  • pry - Using as default Interactive Ruby console instead of irb. Needs some configuration to be hooked as rails console.
  • factory_girl_rails - The testing factory framework, used instead of the default Fixtures.
  • database_cleaner - Used to speed-up tests, in my case to encapsulate the tests into db transaction.
  • awesome_print - Used by Pry to pretty prints Ruby objects in full color exposing their internal structure with proper indentation.
  • capybara - for simulating the web interaction in the tests.
  • guard-rspec - To refresh and run the tests upon saving via rb-fsevent.
  • spork - The server to speed up tests, how?, see provided link.
  • guard-spork - Refreshes the spork server on changes, so that we don’t need to.

Testing configuration

RSpec

RSpec will be used as the test framework for the Just ToDo it app.

Run generator to install RSpec to Rails:

1
2
3
4
$ rails g rspec:install
create  .rspec
create  spec
create  spec/spec_helper.rb

Guard

1
2
3
$ bundle exec guard init
rspec guard added to Guardfile, feel free to edit it
spork guard added to Guardfile, feel free to edit it

Configure Guardfile set the Spork on top and RSpec in bottom:

Guardfile
1
2
3
4
5
6
7
8
9
10
11
12
guard 'spork', :cucumber_env => { 'RAILS_ENV' => 'test' }, :rspec_env => { 'RAILS_ENV' => 'test' } do
  watch('config/application.rb')
  watch('config/environment.rb')
  watch(%r{^config/environments/.+\.rb$})
  watch(%r{^config/initializers/.+\.rb$})
  watch('spec/spec_helper.rb')
  watch(%r{^spec/support/.+\.rb$})
end

guard 'rspec', cli: "--drb" do
  ...
end

Spork

Bootstrap the Spork:

1
2
3
4
$ spork --bootstrap
Using RSpec
Bootstrapping /Users/xajler/src/rb/just-todo-it/spec/spec_helper.rb.
Done. Edit /Users/xajler/src/rb/just-todo-it/spec/spec_helper.rb now with your favorite text editor and follow the instructions.

RSpec Helper

Edit RSpec helper:

1
$ vim spec/spec_helper.rb

And edit to include this content:

spec_helper.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
require 'rubygems'
require 'spork'
require 'database_cleaner'

Spork.prefork do
  ENV["RAILS_ENV"] ||= 'test'
  require File.expand_path("../../config/environment", __FILE__)
  require 'rspec/rails'
  require 'capybara/rspec'

  Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

  DatabaseCleaner.strategy = :truncation

  RSpec.configure do |config|
    config.mock_with :rspec
    config.include FactoryGirl::Syntax::Methods
    config.use_transactional_fixtures = true
    config.infer_base_class_for_anonymous_controllers = false
    config.order = "random"
   end
end

Spork.each_run do
  FactoryGirl.reload
  DatabaseCleaner.clean
end

It uses Spork server and the aim is to have most things in prefork block where is stuff run on load of Spork.

In each_run block we want put only necessary things, because it runs each time, we are now having only reloading of Factory Girl factories, but maybe we will add something from prefork if we would have some troubles with testing data.

DatabaseCleaner is used to start, on before and clean it, on after running. The strategy used for DatabaseCleaner is transaction, meaning to rollback changes after the transaction queries are finished.

Run Guard

The testing environment is now configured, the Guard can be run:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$ guard
uard could not detect any of the supported notification libraries.
Guard is now watching at '/Users/xajler/src/rb/just-todo-it'
Starting Spork for RSpec
Using RSpec
Preloading Rails environment
Loading Spork.prefork block...
Spork is ready and listening on 8989!
Spork server for RSpec successfully started
Guard::RSpec is running
Running all specs
Running tests with args ["--drb", "-f", "progress", "-r", "/Users/xajler/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/guard-rspec-2.1.0/lib/guard/rspec/formatter.rb", "-f", "Guard::RSpec::Formatter", "--out", "/dev/null", "--failure-exit-code", "2", "spec"]...
No examples found.


Finished in 0.11748 seconds
0 examples, 0 failures

Randomized with seed 7715

Done.

or use bundle exec guard to remove displayed warning.

To exit or stop the guard command use Ctrl+C.

Pry as Rails Console

And for the end we will set Pry as our default Interactive Ruby console.

Open the development.rb:

1
$ vim config/enironments/development.rb

At the end of source file add code:

1
2
3
4
silence_warnings do
  require 'pry'
  IRB = Pry
end

Try it out with .pwd and close the Pry with exit command:

1
2
3
4
5
$ rails c
Loading development environment (Rails 3.2.8)
1.9.3 (main):0 > .pwd
/Users/xajler/src/rb/just-todo-it
1.9.3 (main):0 > exit

Commit Source

First remove the README.rdoc file and create markdown README.md:

1
2
$ rm README.rdoc
$ vim README.md

Add simple description:

README.md
1
The simple ToDo Rails App!

Initialize

Initialize the git repository:

1
2
$ git init
Initialized empty Git repository in /Users/xajler/src/rb/just-todo-it/.git/

Status

See the status:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
$ git status
# On branch master
#
# Initial commit
#
# Untracked files:
# .gitignore
# .rspec
# Gemfile
# Gemfile.lock
# Guardfile
# README.md
# Rakefile
# app/
# config.ru
# config/
# db/
# doc/
# lib/
# log/
# public/
# script/
# spec/
# vendor/
nothing added to commit but untracked files present

Add

Then add all files:

1
2
3
4
5
6
7
8
9
10
$ git add .
# On branch master
#
# Initial commit
#
# Changes to be committed:
# new file:   .gitignore
# new file:   .rspec
# new file:   Gemfile
...

Commit

Commit the files to local repository:

1
2
3
4
5
6
$ git commit -m 'Initial Commit. Created initial Rails app, added all needed Gems, testing configured'
[master (root-commit) e4517a6] Initial Commit. Created initial Rails app, added all needed Gems, testing configured
 38 files changed, 1086 insertions(+)
 create mode 100644 .gitignore
 create mode 100644 .rspec
 create mode 100644 Gemfile

Set Github Remote

The app will be on Github. So after the new repository is created on Github, we can add remote to the local repository:

1
$ git remote add origin git@github.com:xajler/just-todo-it.git

Push to the Github

After we add remote, it is now safe to push changes to Github remote repository:

1
2
3
4
5
6
7
8
9
$ git push -u origin master
Counting objects: 63, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (47/47), done.
Writing objects: 100% (63/63), 23.32 KiB, done.
Total 63 (delta 2), reused 0 (delta 0)
To git@github.com:xajler/just-todo-it.git
 * [new branch]      master -> master
Branch master set up to track remote branch master from origin.

Conclusion

It this first part we have created a JustToDoIt Rails application.

And because we shall use TDD (Test Driven Development) to drive this app, we first configure the testing environment including:

  • RSpec
  • Factory Girl
  • Database Cleaner
  • Guard
  • Spork

And for the end we setup the Pry to be a default for Rails console and commit the source to the Github repository xajler/just-todo-it.

In second post we shall go with the creating the app logic in TDD way!

Code

The code is hosted on GitHub and can be cloned from the xajler/just-todo-it.

Github xajler/just-todo-it commit for this post:

Initial Commit. Created initial Rails app, added all needed Gems, testing configured

Comments