Automatic page refresh using Ajax

Ajax On Rails 1 Comment »

Recently, I had come through a requirement where in I had a form which on submitting runs a sql query to get the data from the database based on the submitted form values.Here the primary requirement was to reload the form after every one minute with the same form data to be passed recursively until the user does not modify it.

So whille the solving this issue, I had come through the following approaches for implementing the Auto Refresh while maintaining the form data:

Approach 1:

The HTML Based META Refresh

I feel that this approach is the best when refreshing a static webpage.

It involves the following syntax

<meta http-equiv=”refresh” content=”60;url=http://localhost:3000/admin?param1=params1&params2=param2″>

Here the content = 60 tell the web browser to refresh the page after every 60 seconds the url maps the link to refreshed.

Note: Now when coming to RoR, The url will just represent the action name somewhat like

content=”60;url=/action?param1=params1&params2=param2″

The caveat in this method that I found for my requirement was I had form with many fieldsets and form helpers so the string that i passed to url seemed to be looking very ugly.So I decided to go for the ajax based page refresh whcih looks something cooler then this.

Approach 2 :(Recommended)

The Ajax Periodical Updater

I feel this is the coolest way and the one line code to achieve thsi functionality is use the ajax periodical updater. It comes as a Ajax based Rails helper whisch is formatted as follows

<%=periodically_call_remote(:update => “myDiv”,:frequency => 60, :url => { :action => “action_name”, :params=>params }) %>

Here I am updating the div with id as “myDiv” and relading the same at a time interval of 60 secs.I had to place this div at the immediate start of the HTML body tag and before the immediate end of the body tag as my requirement was a full page reload.

The periodically_call_remote is rendered in the HTML Template as follows

<script type=”text/javascript”>
//<![CDATA[
new PeriodicalExecuter(function() {new Ajax.Updater(’myDiv’, ‘/action_name?params1=params1& params2=params2, {asynchronous:true,evalScripts:true})}, 20)
//]]>
</script>

So wrapping up, I would like to say that the moral of this post I would like to ajax can be used to refresh the page, there by breaking the bounds of the so called REST architecture.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • blogmarks
  • Book.mark.hu
  • co.mments
  • Technorati
  • YahooMyWeb
  • IndianPad
  • DZone

Test Driven Development in RoR

RoR Testing No Comments »

Here’s TDD- new code developement technology in this rails jungle that make the business processes clearer for developers …..
Here we use the test to drive the code…..not the code to make the tests crazy..
Just starting of with a few points for u here which will track u down on the base of TDD

Test Driven Design
aka “Test First”
Drives design desisions through testing.
Ensures things are testable.•
Provides a fast and tight feedback loop.
Attacks the problem at the specification level.
Doesn’t wait until the last minute to see if things work.

TDD Mantra On The Go
•Red - produce failing testcase
•Failures should make you happy!
•Go Green - implement and pass test
•Refactor - clean up - made safer by previous two steps
•Repeat until done

Lets Think Practically:
Im using a simple bank account example for the TDD clearence in u r minds

class AccountTest < Test::Unit::TestCase
def test_new_account_should_have_zero_balance
account = Account.new
assert_equal 0, account.balance
end
end
Its time to run the test:
E 1) Error: test_new_account_should_have_zero_balance:
NameError: uninitialized constant Account ./test/unit/account_test.rb:6:in `test_new_account_should_have_zero_balance’
1 tests, 0 assertions, 0 failures, 1 errors

Oppsss..got a name error… yahh..i got it.. i think i have to play with migrations now… since our failing test is crying taking the name error
class CreateAccount < ActiveRecord::Migration
def self.up create_table “accounts”, :force => true do |t|
t.column :balance, :integer, :default => 0
end
end
end

We will leave the model as it is for the timebeing….lets not play with it…
class Account < ActiveRecord::Base
end

Then we run the test again to make is pass…lets see…
Started . Finished in 0.055268 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
Hurray…that looks pretty good…

Lets depoesit some money into the account…we write the test first..
class DepositTest < Test::Unit::TestCase
def test_should_update_balance_when_making_deposit
account = Account.new account.deposit(10)
assert_equal 10, account.balance
end
run the test…
E 1) Error: test_should_update_balance_when_making_deposit(DepositTest): NoMethodError: undefined method `deposit’ for #
./test/unit/deposit_test.rb:8:in`test_should_update_balance_when_making_deposit’
2 tests, 1 assertions, 0 failures, 1 errors

Oh..Yeahh..It failed again….

The model comes into the picture now:
class Account < ActiveRecord::Base
def deposit(amount)
end
end
Just a little change …and we run the test back again..
1) Failure: test_should_update_balance_when_making_deposit:
<10> expected but was
<0>.
2 tests, 2 assertions, 1 failures, 0 errors
Ohhh…My assertion failed….I think I need to add more in the model…
class Account < ActiveRecord::Base
def deposit(amount)
self.balance += amount #adding the amount to the existing balance
end
end
Finally run the test again….It should pass everything…
Started..Finished in 0.242602 seconds.
2 tests, 2 assertions, 0 failures, 0 errors
Yup…Im on TDD…Its really that simple…!

Moral of the story:

  • With TDD u can can have a total control over your code and application working..
  • We really dont need any testers banging their head doing out some testing on a full proof code developed through TDD technique…
  • Enhances better code refactoring methods and also assures better code coverage for the tests…
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • blogmarks
  • Book.mark.hu
  • co.mments
  • Technorati
  • YahooMyWeb
  • IndianPad
  • DZone

Unit testing in Rails: How To???

RoR Testing 1 Comment »

Steps in unit testing:

Unit test are mainly used to test the models in Rails.
Generally, there is one test for each model.
Unit testing involves testing the databases and the business rules in the model.
Default test Stub are created when you run script/generate model

Division of a unit test:
· GENERATION OF A TEST DATABASE
· WRITING THE UNIT TEST CASES INCLUDING ASSERTIONS.
· LOADING THE .YML FILE WITH DEFAULT VALUES
· RUNNING THE TEST CASE.

Writing the unit test case involves the following steps:
The first steps in the unit test case involves creation of the test database for the testing purpose which can be generated from the following command:
rake clone_structure_to_test or rake db:test:clone_structure
All the test cases for the models are written under the /test/unit directory.
The test class is the is the subclass of the Test::Unit::TestCase base class which tells the rails to generate the tests based on the Test::Unit framework.
Assertions can be used to test the necessary checkpoints within the test case.
Assertions are triggers which validate or test the current state of a webapp during the runtime.
After the preparation of the test case, we load the test database with some default data using fixtures.
Fixtures are available under the test/fixtures directory under the webapp.
We edit the .yml file to match the records in the test database and load the records with some default data.
To run the test we use the following command:
rubytest/unit/.rb

Checking The Code Coverage Of The Test:Using RCOV

Rcov takes the .rb files as the input and checks the code coverage of the test on the model file and generates the code coverage statistics as a html files and stores it in the folder named coverage in your webapp.
Optimizations then need to done on the .rb file until it shows a code coverage of almost 95-100%

Assertions:
The following is the list of assertions that can be used while writing the unit test cases:
Note:The [msg] is an optional string message you can specify to make your test failure messages clearer. It’s not required.
*assert* ( boolean, [msg] ) … ensures the object/expression is true
*assert_equal* ( obj1, obj2, [msg] ) … ensures obj1 obj2 is true @*assert_not_equal* ( obj1, obj2, [msg] )@ … ensures obj1 obj2 is false
*assert_same* ( obj1, obj2, [msg] ) … ensures obj1.equal?(obj2) is true
*assert_not_same* ( obj1, obj2, [msg] ) … ensures obj1.equal?(obj2) is false
*assert_nil* ( obj, [msg] ) … ensures obj.nil? is true
*assert_not_nil* ( obj, [msg] ) … ensures obj.nil? is false
*assert_match* ( regexp, string, [msg] ) … ensures a string matches the regular expression
*assert_no_match* ( regexp, string, [msg] ) … ensures a string doesn’t matches the regular expression
*assert_in_delta* ( expecting, actual, delta, [msg] ) … ensures the numbers expecting and actual are within delta of each other
*assert_throws* ( symbol, [msg] ){ block } … ensures a block throws the symbol
*assert_raises* ( exceptions ){ block } … ensures a block raises one of the comma-separated exceptions
*assert_nothing_raised* ( exceptions ){ block } … a block doesn’t raise one of the comma-separated exceptions
*assert_instance_of* ( class, obj, [msg] ) … ensures obj is the class type
*assert_kind_of* ( class, obj, [msg] ) … ensures obj is or descends from class
*assert_respond_to* ( obj, symbol, [msg] ) … ensures obj has a method called symbol
*assert_operator* ( obj1, operator, obj2, [msg] ) … ensures obj1.operator(obj2) is true
*assert_send* ( array, [msg] ) … ensures that executing the method listed in array[ 1 ] on the object in array[ 0 ] with the parameters of array[ 2 and up ] is true. This one is weird eh?
*flunk* ( [msg] ) … ensures the failure of the test

Here is a Demo example:
Example :Person Test: /test/unit/person_test.rb
require File.dirname(__FILE__) + ‘/../test_helper’
fixtures :person
class PersonTest < Test::Unit::TestCase
def setup
@people = Person.new
end
def test_something
#Write your test cases along with the necessary assertions here.
assert true, “Test implementation missing”
end
end

#example of the password test case.
def test_passwords
jimmy = Person.new
jimmy.first_name = ‘Jimmy’
jimmy.last_name = ‘McJimmy’
jimmy.password = ‘h1st0r3ct@my’
#The assertion lineup
assert !jimmy.password.empty?
assert jimmy.password.length > 5
assert_match /(0-9)/, jimmy.password
assert_not_equal ‘password’, jimmy.password.downcase
end

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • blogmarks
  • Book.mark.hu
  • co.mments
  • Technorati
  • YahooMyWeb
  • IndianPad
  • DZone

WordPress Theme & Icons by N.Design Studio. Packaged by Edublogs - education blogs.
Entries RSS Comments RSS Login