↓ Archives ↓

Posts Tagged → rspec

Coding Screencasts

I’ve been doing some programming screencasts lately over my Youtube channel. They’re not really “screencasts” ala RailsCasts but more like informal streamed videos that you’d see in Justin.tv/Twitch.tv.

These screencasts were recorded in 720p so it’s a good idea to select a higher resolution then view the videos in full screen or the large player in order for you to read the code properly.

Here I code a hexagonal “game of life”-like cellular automata. Used Ruby, Gosu, and RSpec.

Walking through coding a simple Rails app. Bunch of technologies discussed like Twitter Bootstrap, Heroku, and git.

Going through Project Euler problems via brute force using Java.

This post by Bryan Bibat is from existence, refactored.

Starting a “professional” Rails 3.1 app with Web App Theme, Devise, and Kaminari

With the recent release of web-app-theme providing Rails 3.1 support, it’s time once again for me to write a tutorial on how to earn money from cheap clients who can’t afford designers.

For reference, the previous tutorial can be read here.

crud screen

Every Rails developer knows how to create a Rails app. It’s easy as

rails new APP-NAME-HERE

But how many know how to create an app from scratch that looks good enough to sell to clients i.e. with slick design, authentication, authorization, and all that? Sure, there are tutorials out there that cover those components, but most of them cover them only in isolation from each other. A quick tutorial containing multiple components at a time would be a valuable resource to anyone planning to start a new app.

As the resident dilettante in these parts, I’ve decided to create such a tutorial based on a recent demo I made for a prospective client.

This post will discuss how to create a Rails 3.1 application that looks good enough to sell to clients (of course, YMMV) while still having components found in “professional” apps. This tutorial will cover the following:

  • Andrea Franz’s web-app-theme gem – this gem generates themes for your web app (hence the name). The demo and the list of available themes can be found on this page.
  • Devise – our authentication module. Authlogic‘s fine, but I find Devise’s approach less obtrusive.
  • Haml – replaces Erb. Not perfect (e.g. screws up with inline a tags) but the drastic decrease in code makes passing it up difficult.
  • Rspec – replaces Test::Unit. Only setup will be covered in this post, actual usage is left to the reader.
  • Kaminari – gem for pagination. We’re going to use it in place of the previous gem will_paginate

Rest of the tutorial is below the cut.

Let’s start by creating our new app with no testing framework and with MySQL as the database:

$ rails new pro-template-app-31 -d mysql -T

Now would be a good time to edit the .gitignore file to exclude files you don’t want to add to Git. Rails 3 already provides some good defaults, but if you want more possible entries there are samples available over at Github.

Once done, it’s time to make the initial commit.

$ git init
$ git add .
$ git commit -am "initial commit"

Setup Gemfile

Now is time to add the needed gems to Gemfile.

source 'http://rubygems.org'

gem 'rails', '3.1.0'
gem 'mysql2'
gem 'haml'
gem 'devise'
gem 'kaminari'

group :development, :test do
  gem 'capybara'
  gem 'rspec-rails'
  gem 'haml-rails'
  gem 'hpricot'
  gem 'ruby_parser'
  gem 'web-app-theme', '~> 0.8.0'
end

I’ve already explained most of the gems above at the beginning of this post. The only thing worth noting would be the addition of hpricot and ruby_parser, both of which are needed by web-app-theme to generate haml files.

Run “bundle install” to install the gems. After the gems are installed, all of our generators will now use Rspec instead of Test::Unit, and it can now generate Haml instead of Erb.

Generate home page

Let’s try out our app first by creating a new root page to replace the default.

$ rails g controller home index
 
$ rm public/index.html

Then edit the config/routes.rb:

ProTemplateApp31::Application.routes.draw do
  root :to => "home#index"
end

Before starting the app, don’t forget to create the database:

$ rake db:create

Start the server.

initial root page

all pictures are clickable BTW

Generate theme with web-app-theme

Here comes the fun part.

$ rails g web_app_theme:theme --engine=haml --app-name="My Latest Web App"

This will generate the layout files using the default theme in haml whose title would be “My Latest Web App”.

(In case you want to use a different theme, add --theme="THEME-NAME" to this and some of the later commands.)

Delete the default layout generated for the rails app:

$ rm app/views/layouts/application.html.erb

then refresh the page.

themed root page

It looks good, but I think we’re better off using the sample text page from the demo site.

$ rails g web_app_theme:themed home --themed-type=text --engine=haml
 
$ mv app/views/home/show.html.haml app/views/home/index.html.haml

fixed home page

Tweaking web-app-theme v0.8.0

Before we continue, let’s first fix some problems with web-app-theme 0.8.0 when used with Rails 3.1.

First, generate a copy of the current theme to your app so that you could modify them.

$ rails g web_app_theme:assets

Now for the tweaks:

  • JavaScript tag doesn’t point to the one generated by the asset pipeline. This is the reason why the sign-out links won’t work if you followed the previous tutorial. Fix here.
  • The stylesheet for alert messages are still defined under “error” class. Fix here.
  • For some odd reason, the images for buttons were moved to the spec folder. You can bring them back by manually copying them to your project’s web-app-theme asset folder. Here’s one way of doing it:

$ cp $(bundle show web-app-theme)/spec/dummy/public/images/* app/assets/images/web-app-theme/ -r

Add Devise authentication

Let’s install Devise and create our User model in the process.

$ rails g devise:install
 
$ rails g devise user

We also need to customize the login screen. To do this, we must first enable scoped views for Devise.

Then let’s generate the sign-in/sign-out layout:

$ rails g web_app_theme:theme sign --layout-type=sign --engine=haml --app-name="My Latest Web App"

Then let’s add the following files to the config/application.rb file to change the layout for sign-in/sign-up:

    config.to_prepare do
      Devise::SessionsController.layout "sign"
      Devise::RegistrationsController.layout "sign"
    end

At this point, you could generate the Devise views via

$ rails g devise:views

but the generated files are in ERb, not to mention that the layout for the sign-in/sign-up pages are different from what web-app-theme expects.

To save you from the hassle of copying the layout of those two pages, you could just copy-paste what I did here and here.

Restart the server, run rake db:migrate, and try going to the login site (/users/sign_in).

login page

Clicking “Sign up”:

sign up page

Finishing touches to Devise

Let’s do some finishing touches to the UI.

First, modify the layout such that the logout button actually works.

Now to test if Devise really works. Add the before_filter :authenticate_user! to home_controller.rb to kick us out to the login screen if we’re not logged in. While we’re at it, modify the said controller to set tell sign-out to redirect to the sign-in page.

login error

Create a test user via the rails console.

$ rails c

User.create :email => "test@example.com", :password => "123456", :password_confirmation => "123456"

You should now be able to login and logout.

login success

logout success

Theming a CRUD module

Now let’s show how to add the web-app-theme to a new CRUD module. To simplify things, we’ll use the ultra-stupidsimple blog demo.

$ rails g scaffold blog_entry subject:string content:text publish_at:datetime
...
$ rake db:migrate

Overwrite the generated files by running web-app-theme’s generator:

$ rails g web_app_theme:themed blog_entries --will-paginate --engine=haml

Since we’re using kaminari, we need to modify the controller and index page accordingly.

We will also have to modify the kaminari template to match the CSS. First generate the view files via

$ rails g kaminari:views default -e haml

then modify the files to match the layout with the demo page. Here’s one way of doing it.

We also need to modify the layout to take into account the new module.

crud screen

After that, you can still do a couple of minor tweaks to the pages to deal with their “auto-generated” jagged edges. Then you can also apply the error message fix (don’t forget to restart the server) and test it with the screens.

fixed crud

And that’s it. The complete code generated above can be found at Github.

This post by Bryan Bibat is from existence, refactored.

Starting a “professional” Rails app with Haml, Rspec, Devise, and Web App Theme

crud screen

Every Rails developer knows how to create a Rails app. It’s easy as

rails new APP-NAME-HERE

But how many know how to create an app from scratch that looks good enough to sell to clients i.e. with slick design, authentication, authorization, and all that? Sure, there are tutorials out there that cover those components, but most of them cover them only in isolation from each other. A quick tutorial containing multiple components at a time would be a valuable resource to anyone planning to start a new app.

As the resident dilettante in these parts, I’ve decided to create such a tutorial based on a recent demo I made for a prospective client.

This post will discuss how to create a Rails 3 application that looks good enough to sell to clients (of course, YMMV) while still having components found in “professional” apps. This tutorial will cover the following:

  • Andrea Franz’s web-app-theme gem – I only recently found out about this theme generator gem. Had I discovered this sooner, I might not have made “I hate web design” a catchphrase. Basically this gem generates themes for your web app (hence the name). The demo and the list of available themes can be found on this page. The main downside to this gem is the lack of tutorials on the net about it. Hopefully this post will give people an idea what to expect with the gem.
  • Devise – our authentication module. Authlogic‘s fine, but I find Devise’s approach less obtrusive.
  • Haml – replaces Erb. Not perfect (e.g. screws up with inline a tags) but the drastic decrease in code makes passing it up difficult.
  • Rspec – replaces Test::Unit. Only setup will be covered in this post, actual usage is left to the reader.
  • will_paginate – gem for pagination. Everybody uses it, so what the hell…

Rest of the tutorial is below the cut.

Let’s start by creating our new app with no testing framework and with MySQL as the database:

$ rails new pro-template-app -d mysql -T

Now would be a good time to edit the .gitignore file to exclude files you don’t want to add to Git. Rails 3 already provides some good defaults, but if you want more possible entries there are samples available over at Github.

Once done, it’s time to make the initial commit.

$ git init
$ git add .
$ git commit -am "initial commit"

Setup Gemfile

Now is time to add the needed gems to Gemfile.

source 'http://rubygems.org'

gem 'rails', '3.0.3'
gem 'mysql2'
gem 'haml'
gem 'will_paginate', '3.0.pre2'
gem 'devise'

group :development, :test do
  gem 'capybara'
  gem 'rspec-rails'
  gem 'haml-rails'
  gem 'hpricot'
  gem 'ruby_parser'
  gem 'web-app-theme'
end

I’ve already explained most of the gems above at the beginning of this post. The only thing worth noting would be the odd version of will_paginate (no “release” version is ready yet for Rails 3) and the addition of hpricot and ruby_parser, both of which are needed by both devise and web-app-theme to generate haml files.

Run “bundle install” to install the gems. After the gems are installed, all of our generators will now use Rspec instead of Test::Unit, and it can now generate Haml instead of Erb.

Generate home page

Let’s try out our app first by creating a new root page to replace the default.

$ rails g controller home index
 
$ rm public/index.html

Then edit the config/routes.rb:

ProTemplateApp::Application.routes.draw do
  root :to => "home#index"
end

Before starting the app, don’t forget to create the database:

$ rake db:create

Start the server.

initial root page

Generate theme with web-app-theme

Here comes the fun part.

$ rails g web_app_theme:theme --theme="drastic-dark" --engine=haml --app-name="My Latest Web App"

This will generate the layout files using the “Drastic Dark” theme in haml whose title would be “My Latest Web App”.

Delete the default layout generated for the rails app:

$ rm app/views/layouts/application.html.erb

then refresh the page.

themed root page

It looks good, but it’s a little bit off when compared to the sample page. We still need to tweak the pages a bit. Look here and here for the changes to the page and layout respectively.

fixed home page

Jan 10 update: Andrea Franz also mentioned that you could use the option --themed-type=text for this step to generate a text template which you could manipulate as needed.

Note that the file created would be show.html.haml so unless you decided to treat the home controller as a resource (i.e. use show instead of index as the default page), you will have to rename/overwrite the said files.

$ rails g web_app_theme:themed home --themed-type=text --engine=haml
 
$ mv app/views/home/show.html.haml app/views/home/index.html.haml

Add Devise authentication

Let’s install Devise and create our User model in the process.

$ rails g devise:install
 
$ rails g devise user

We also need to customize the login screen so we’ll generate the Devise views.

rails g devise:views -e haml

Now we need to tweak the UI to use the web-app-theme. First, let’s generate the sign in layout:

$ rails g web_app_theme:theme sign --layout-type=sign --theme="drastic-dark" --engine=haml --app-name="My Latest Web App"

Then let’s add the following files to the config/application.rb file to change the layout for signing in:

    config.to_prepare do
      Devise::SessionsController.layout "sign"
    end

After that comes the tedious part of having to modify the Devise app/views/devise/sessions/new.html.haml file to match the one expected by web-app-theme. Fortunately for you, you could just copy-paste what I did here.

Restart the server, run rake db:migrate, and try going to the login site (/users/sign_in).

login page

Finishing touches to Devise

Let’s do some finishing touches to the UI.

First, modify the layout such that the logout button actually works. Then modify the CSS to use the Rails 3 standard “alert” flash message instead of “error”.

Now to test if Devise really works. Add the before_filter :authenticate_user! to home_controller.rb to kick us out to the login screen if we’re not logged in.

login error

Create a test user via the rails console.

$ rails c

User.create :email => "test@example.com", :password => "123456", :password_confirmation => "123456"

You should now be able to login and logout.

login success

Theming a CRUD module

Now let’s show how to add the web-app-theme to a new CRUD module. To simplify things, we’ll use the ultra-stupidsimple blog demo.

$ rails g scaffold blog_entry subject:string content:text publish_at:datetime
...
$ rake db:migrate

Overwrite the generated files by running web-app-theme’s generator:

$ rails g web_app_theme:themed blog_entries --will-paginate --engine=haml

Since we’re using will_paginate, we need to modify the controller accordingly. We also need to modify the layout to take into account the new module.

crud screen

After that, you can still do a couple of minor tweaks to the pages to deal with their “auto-generated” jagged edges. Then you can also apply the error message fix and test it with the screens.

fixed crud

And after that…

The rest is up to the reader. Here are some gems that you might want to look at for your application, though:

  • Cancan – clients usually have roles in their apps. If you have more than 3 roles, I suggest you use this gem to manage user rights.
  • Delocalize – add this gem unless you want to manually handle your clients entering 10,000.00, saving it as 10000.00 in the database instead of 10. Also works on dates.
  • Spreadsheet – web apps usually have a Batch Job and Reports component. While I’ve gone by with using the “runner + cron” for batch jobs, clients don’t really find CSV reports appealing. This gem allows you to generate Excel reports for them.
  • Capistrano – for deployment. This gem warrants its own tutorial.

And that’s it. The complete code generated above can be found at Github.

This post by Bryan Bibat is from existence, refactored.

How to avoid breaking builds

git The guy I’m mentoring right now in one of my freelancing gigs is fairly new to software development so I decided to give him a couple of guidelines (conveniently posted on the project’s wiki) on how to properly use git. Hopefully this should spare me the horrible flashbacks to the days when everyone I was working with was consistently breaking builds everyday.

Best Practices

  • Commit often. The more you commit, the easier it is to do stuff like rolling back changes or pinpointing where a change was committed.
  • Put a meaningful comment every commit. You’ll be thankful you did that 3-6 months down the line when you’re trying to verify if a certain piece of code is a bug or a feature.
  • Push with care. Follow the procedure below to avoid breaking the build i.e. pushing a version of the code which doesn’t work.

Proper Version Control Procedure

Before you push your code to the repository, please follow the following procedure:
  • If you still haven’t done it yet, commit your changes to your local repository (git add and/or git commit -a -m).
  1. Pull the changes from the remote repository (git pull).
  2. In case of conflict, manually edit the conflicting files.
    • You may have to collaborate with the other dev for this.
    • After fixing the conflict, commit the merged changes and go back to step 1 (git pull).
  3. Run the DB migrations.
  4. Run the RSpec tests.
    • If the specs fail, either fix the code or fix the specs.
    • After fixing the failing specs, commit the fixes and go back to step 1.
  5. Run the Cucumber tests.
    • If the specs fail, either fix the code or fix the features.
    • After fixing the failing features, commit the fixes and go back to step 1.
  6. Do a simple developer test. Open the server, log in, and open a couple of pages.
    • If the system doesn’t work, find the problem and fix it.
    • After making the system run smoothly again, commit the fixes and go back to step 1.
  7. You can now push your changes to the remote repository using git push.
You might notice that we’re using RSpec and Cucumber in our project. I’ll talk more about them in a later post.

This post by Bryan Bibat is from existence, refactored.

Learn RSpec in 15 Minutes or Less

You can learn RSpec in less than 15 minutes especially if you are not Rails newbie. RSpec and BDD is a way of getting an application done right in an unbelievably short period of time.

BDD is behaviour-driven development. You think about all the specification and expectations regarding a project before working on it. That's what most software developers normally do. I spend at least one day just thinking about specifications and based on experience - I think about several details like:

  1. User Interface (Look and feel)
  2. Project Goals (What makes the application fun? Who are your audience? How can you profit from the project?)
  3. Plugins and Gems required by the project
  4. Key Features - (What feature can't be deferred?)
  5. What can go wrong? (OOP is now pronounced "uh-oh P")

Regarding number 3 and 4, they are quite related and it usually takes over a day to think about everything. For number 5, I usually don't stress about it but I do consider things like server issues.

Let's do another blog application :

#on config/environments/test.rb

config.gem 'rspec-rails', :lib=>false
config.gem 'rspec', :lib=>false
config.gem 'cucumber', :lib=>false

Do rake gems:install RAILS_ENV=test

script/generate rspec_scaffold Post user_id:integer title:string body:text

The code above generates everything - MVC + Spec tests. Someone asked me if I do use the default scaffolds in Rails. I do use scaffolding but with RSpec (rspec_scaffold).

Adding Authlogic for authentication. (If required later, you can try declarative authorization or role requirement for role-based authorization.)


script/plugin install git://github.com/binarylogic/authlogic.git

Here's a nice write-up on Rspec and authlogic.

A more real-world example of an rspec model test (taken off a previous project of mine) of RSpec:


#in spec/models/article_spec.rb 

require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe Article do
  before(:each) do
    @article = Article.new
    @filename = "01.jpg"
    @file_type = "image/jpeg"
    @file_size = "304986"
    @file_updated_at    = Time.now
    @date = Time.now
  end

  it "should not be valid when empty" do
    @article.should_not be_valid
  end

  ['user_id, title, body, category_id, date'].each do |field|
    it "should require #{field}" do
     @article.should_not be_valid
    end
  end
  
  it "should be valid when details are not empty" do
    @article.user_id = 1
    @article.title = "A long day and things are still not right"
    @article.body = "There are many variations of passages of 
Lorem Ipsum available, but the majority have suffered 
alteration in some form, by injected humour, or randomised words 
which don't look even slightly believable. 
If you are going to use a passage of Lorem Ipsum, you need 
to be sure there isn't anything embarrassing hidden in the 
middle of text.

All the Lorem Ipsum generators on the Internet tend to 
repeat predefined chunks as necessary, making this the first 
true generator on the Internet. 
It uses a dictionary of over 200 Latin words, 
combined with a handful of model sentence structures, 
to generate Lorem Ipsum which looks reasonable. 
The generated Lorem Ipsum is therefore always free 
from repetition, injected humour, or non-characteristic 
words etc."
    @article.category_id = Category.new
    @article.photo_file_name = @filename
    @article.photo_content_type = @file_type
    @article.photo_file_size = @file_size
    @article.photo_updated_at = @file_updated_at
    @article.date = @date
    @article.should be_valid
  end


end

RSpec in Rails 3

Based on observation, RSpec has better acceptance in the rails community than the default test suite. I am expecting Rails 3 book to cover more about automated testing with RSpec.

Happy New Year! I love Rails and all the people working hard to make it better.

This post by Katz Pe is from BridgeUtopia.