Veerasundaravel's Ruby on Rails Weblog

July 25, 2012

Rspec Shoulda-Matcher made Unit testing as easier one

Filed under: Rails3, Ruby, Ruby On Rails, Testing, Unit Test — Tags: , , , , , , — Veerasundaravel @ 12:37 am

Shoulda matcher is a library that enables to write better and more understandable tests for Rails application. It is Test::Unit- and RSpec-compatible one-liners that test common Rails functionality.

Here few very easier example of shoulda-matchers for Unit Testing.

Test model fields:

it {should have_db_column(:login)}
it {should have_db_column(:salary).of_type(:decimal).with_options(:precision => 10, :scale => 2) }
it { should_not have_db_column(:admin).of_type(:boolean) }

Test db indexes:

it { should have_db_index(:age) }
it { should have_db_index([:commentable_type, :commentable_id]) }
it { should have_db_index(:ssn).unique(true) }

Test validations:

it { should validate_uniqueness_of(:title) }
it { should validate_presence_of(:body).with_message(/Enter the message/) }
it { should validate_presence_of(:title) }
it { should validate_numericality_of(:user_id) }
it { should validate_uniqueness_of(:title) }
it { should_not allow_value("blah").for(:email) }
it { should allow_value("a@b.com").for(:email) }
it { should ensure_inclusion_of(:age).in_range(1..100) }
it { should_not allow_mass_assignment_of(:password) }

Test associations:

it { should belong_to(:parent) }
it { should have_one(:car)
it { should have_many(:friends) }
it { should have_many(:enemies).through(:friends) }

 

Further reading:

Shoulda-Matcher home page –  https://github.com/thoughtbot/shoulda-matchers/
Shoulda-context home page – https://github.com/thoughtbot/shoulda-context/
rspec_shoulda cheat sheet – http://cheat.errtheblog.com/s/rspec_shoulda/

 

November 18, 2011

link_to_remote With Rails 3 and UJS

Filed under: Rails3 — Tags: , , , , , , , — Veerasundaravel @ 3:46 pm

Rails 3 has adopted Unobtrusive Javascript and moved all the _remote functions to a plugin called prototype_legacy_helper. You can view the release note about this here. They did this in an effort to remove all the inline nasty code produced by the helpers and provide a more modular way to deal with Javascript & Ajax.

What this means is that all previous remote_<method> helpers have been removed from Rails core. To get UJS hooks into your HTML, you can now pass :remote => true instead. For example:

in Rails2:

link_to_remote('Refresh', :update => "emails", :url => {:controller=>"mail", :action => "list_emails" })

#will result

<a href="#" onclick="new Ajax.Updater('emails', '/mail/list_emails', {asynchronous:true, evalScripts:true}); 
return false;">Refresh</a>

 

in Rails3:

link_to 'Refresh', {:controller=>"mail", :action => 'list_emails'}, :remote=> true 

#will result

<a href="/mail/list_emails" data-remote="true">Refresh</a>

This makes it very easy for a javascript driver to come along, pick out and identify the relevant pieces, and attach the appropriate handlers.

Grab the jQuery UJS driver at http://github.com/rails/jquery-ujs and put it in your javascripts directory. The file is at src/rails.js

Include jQuery and the UJS driver in your application layout or view. Then the Rails UJS driver look for links and forms with a data-remote=”true” attribute and AJAX-ify them. So now our <a> tag can fire a Ajax request.

 

Ajax Callbacks:

With good old link_to_remote we could pass an :update option to achieve the system described above, in which the page receives a generic response and updates the specified element with it. But link_to doesn’t accept an :update option because with Rails 3 and UJS we want to avoid putting JavaScript in our <a> tag attributes.

So how do we do this? If we don’t write the code that makes the AJAX request, how can we access the response? The answer is: events.

 

The UJS drivers trigger six events on every AJAX call:

  • ajax:before
  • ajax:loading
  • ajax:success
  • ajax:failure
  • ajax:complete
  • ajax:after

You should recognize these event names from the old link_to_remote method options, and we simply need to listen for them on our AJAX-triggering elements.

 

Example:

Let’s say we have a page that lists the ten most popular products in our database. At the end is a link to load all the remaining products via AJAX:

<ul id="products-list">
  <li>...</li>
  <li>...</li>
  <li>...</li>
 ...
</ul>
<%= link_to "more...", "/products/all", :id => "load-more", :remote => true %>

The server returns plain HTML and we use the ajax:x events triggered by the Rails UJS drivers (here jQuery) to grab the server’s response and insert it into the right element on the page:

<%= javascript_tag do %>
  $("#load-more").bind("ajax:complete", function(et, e){
    $("#products-list").html(e.responseText); // insert content
  });
<% end %>

If desired, we can also use the ajax:loading event to change the link text (or show a spinner):

<%= javascript_tag do %>
  $("#load-more").bind("ajax:loading", function(et, e){
    $(this).html("Loading..."); // swap link text
  });
<% end %>

 

Use the forgery protection meta tags: <%= csrf_meta_tag %>:

This tag will return meta tags with the cross-site request forgery protection token for forms to use. Place this in your head, it will return meta tags as follows:

<metaname="csrf-param"content="authenticity_token"/>
<metaname="csrf-token"content="pACcWm38PxTmGUoz2bSmKIzIwpEmqCJDTH6xe2="/>

Don’t hardcode these tags or values. Also in Rails 3.1, csrf_meta_tag has been renamed to csrf_meta_tags.

November 13, 2011

Localhost alternates for subdomain

Filed under: Ruby On Rails — Tags: , , , , , , , , — Veerasundaravel @ 2:04 am

Most of we Rails developers, used to check our Rails app using http://localhost:3000/. But this particular url have the  following issues.

1. We can’t add/check subdomain with localhost like http://company1.localhost:3000/

2. Some of external API will not work when we are using localhost.

3. More over using system hostname for subdomain also requires too much configuration in host files.

Best way to solve this:

smackaho.st and lvh.me provides good option of using localhost with subdomain etc. The two domains are pointed to localhost only. If we go to http://lvh.me:3000/ we’ll see the homepage of our application because lvh.me resolves to the IP address 127.0.0.1.

Checkout all the below urls. all will open your application homepage.

http://smackaho.st:3000/
http://abc.smackaho.st:3000/
http://lvh.me:3000/
http://xyz.lvh.me:3000/


Related Articles:

tbaggery – Smack a Ho.st
ASCIIcasts – Subdomain in Rails3

« Newer PostsOlder Posts »

%d bloggers like this: