Showing posts with label FreeBSD. Show all posts
Showing posts with label FreeBSD. Show all posts

Thursday, August 9, 2012

Test Driven Development (TDD) in Ruby on Rails

Introduction

The purpose of this document is to describe the working principle of Ruby on Rails test frameworks, its application, advantages and disadvantages. This document contains an introduction to Test driven development (TDD).

Test  Driven Development (TDD)

            Test Driven Development is a development practice which involves writing test cases before writing the code. Start by writing a very small test for code that does not yet exist. Run the test and, naturally, it fails. Now we have to write the code to pass the test.ie, writing code only for the requirement. Large numbers of tests help to limit the number of defects in the code. The early and frequent nature of the testing helps to catch defects early in the development cycle, preventing them from becoming endemic and expensive problems.

TDD in Ruby on Rails
                   Ruby on rails supports test frameworks for Test Driven Development; A Test Framework is a tool or library that provides a backdrop for writing tests. This is an excellent way to build up a test suite that exercises every part of the application.
There are several testing frameworks in use for Ruby today:
  • Test::Unit is included with Ruby 1.8, and follows the "xUnit" conventions
  • Minitest is included with Ruby 1.9, and allows both xUnit and RSpec style tests
  • RSpec, which  has more concise syntax and can be used in the same project, but creates a separate suite of tests, called "specs"
  • In Cucumber, tests are written not in Ruby but in a language designed for tests
  • Rspec-2, which is used with Rails -3. Since We are using Rails -3 Rspec -2 is the best option we can use for test driven development
For using this, we have to twist thinking a little bit. Our goal is not to write eventual production code right away , but our goal is to make our test cases pass.
Work Flow Structure
We can structure the test driven workflow as follows:
  • First write a test: This test describes the behavior of a small element of your system. Tests in TDD are called programmer tests. When writing the tests it should be kept in mind that the tests should concentrate on testing the true behaviors, i.e. if a system has to handle multiple inputs, the tests should reflect multiple inputs.
  • Run the test:  The test definitely fails because you have not yet built the code for that part of your system. This important step tests your test case, verifying that your test case fails. The automatic tests should be run after each change of the application code in order to assure that the changes have not introduced errors to the previous version of the code
  • Write Code: Then only real coding comes, write enough code to make the test pass. In TDD, the code writing is actually a process for making the test work, i.e. writing the code that passes the test.
  • Run the test: Again run the test and verify that they pass.
·         Refactor the code - Refactoring is a process of improving the internal structure by editing the existing working code, without changing its external behavior. The idea of refactoring is to carry out the modifications as a series of small steps without introducing new defects into to the system
  • Run all tests:  To verify that the refactoring did not change the external behavior.
 See the Structure below:
     The first step involves simply writing a piece of code that tests the desired functionality. The second one is required to validate that the test is correct, i.e. the test must not pass at this point, because the behavior under implementation must not exist as yet. Nonetheless, if the test passes, the test is either not testing the correct behavior or the TDD principles have not been followed. The third step is the writing of the code. However, it should be kept in mind to only write as little code as possible to pass the. Next, all tests must be run in order to see that the change has not introduced any problems somewhere else in the system. Once all tests pass, the internal structure of the code should be improved by refactoring.

Rspec2
RSpec is a great tool in the behavior driven design process of writing human readable specifications that direct and validate the development of your application. What follows are some guidelines taken from the literature, online resources, and from our experience. Rspec is not a tool for Integration Testing but for Unit Testing, if you want to set up integration tests, then you should use Cucumber. Cucumber is designed to easy Behavior Driven Development but even if you don't BDD it is perfect for integration testing.
Examples  For Rspec-2  Test case
We can integrate Rspec to Ruby On Rails  by installing the Rspec2 gem.
            gem install rspec-rails

For this example, we’ll describe and develop the beginnings of a User class, which can be assigned any number of roles. Start by creating a directory for the files for this tutorial.
                   
                    * mkdir rspec_example
                    * cd rspec_example

 The first methods we’ll encounter are ` describe` and  `it`.
Create a file in this directory named user_spec.rb  and type the following:

describe User do
end

The describe method creates an instance of Behavior. So “describe User” is really saying “describe the behaviour of the User class”.
Run the following command:
               *  rspec spec/ user_spec.rb

     The rspec command gets installed when you install the rspec-rails gem. It supports   a large number of command line options.
     Running user_spec.rb should have resulted in output that includes the following error:
    ./user_spec.rb:1: uninitialized constant User (NameError)

We haven’t even written a single line of production code and already Rspec2 is telling us what code we need to write. We need to create a User class to resolve this error,



so create user.rb with the following:

class User
end
 And require it in user_spec.rb:
require 'user'

describe User do
end

Now run the rspec command again, will get a result like this
              
Finished in 6.0e-06 seconds
0 examples, 0 failures
The output shows that we have no examples yet, so let’s add one. We’ll start by describing the intent of example without any code.
describe User do
  it "should be in any roles assigned to it" do
  end
end

Run the spec, but this time adds the --format option:

$ rspec spec/user_spec.rb --format doc

User - should be in any roles assigned to it
Finished in 0.022865 seconds
1 example, 0 failures

Now add a Ruby statement that begins to express the described intent.

describe User do
  it "should be in any roles assigned to it" do
    user.should be_in_role ("assigned role")
  end
end

… and run the spec command.

$ rspec spec/user_spec.rb --format specdoc

User - should be in any roles assigned to it (ERROR - 1)

1) NameError in 'User should be in any roles assigned to it' undefined local variable or method `user' for #<#<Class:0x14ed15c>:0x14ecdd8> ./user_spec.rb:6:

Finished in 0.017956 seconds

1 example, 1 failure

The output tells us that there is an error that no user has been defined, so the next step is to make one:

describe User do
  it "should be in any roles assigned to it" do
    user = User.new
    user.should be_in_role ("assigned role")
  end
end

Run the spec command,
$ rspec spec/user_spec.rb --format specdoc

User - should be in any roles assigned to it (ERROR - 1)
1) NoMethodError in 'User should be in any roles assigned to it' undefined method `in_role?' for #<User:0x14ec8ec> ./user_spec.rb:7:
Finished in 0.020779 seconds
1 example, 1 failure

Now we learn that User does not respond to in_role?, so we add that to User:

class User
  def in_role?(role)
  end

$ rspec spec/user_spec.rb --format specdoc

User - should be in any roles assigned to it (FAILED - 1)
1) 'User should be in any roles assigned to it' FAILED expected in_role?("assigned role") to return true, 
got nil ./user_spec.rb:7:
Finished in 0.0172110000000001 seconds
1 example, 1 failure

We now have a failing example, which is the first goal. We always want to see a meaningful failure before 
success because that’s the only way we can be sure the success is the result of writing code in the right place in the system.

To get this to pass, we do the simplest thing that could possibly work:
Edit user.rb

class User
  def in_role?(role)
    true
  end


$ rspec spec/user_spec.rb --format specdoc

User - should be in any roles assigned to it
Finished in 0.018173 seconds
1 example, 0 failures

That passes, but we’re not done yet. Take a look again at the example:

describe User do
  it "should be in any roles assigned to it" do
    user = User.new
    user.should be_in_role("assigned role")
  end
end

The description says that the User “should be in any roles assigned to it”, but we haven’t assigned any roles to
 it. Let’s add that assignment to the example:

describe User do
  it "should be in any roles assigned to it" do
    user = User.new
    user.assign_role("assigned role")
    user.should be_in_role("assigned role")
  end
end

$ rspec spec/user_spec.rb --format specdoc

User - should be in any roles assigned to it (ERROR - 1)
1) NoMethodError in 'User should be in any roles assigned to it' undefined method `assign_role' for
 #<User:0x14ec784> ./user_spec.rb:6:
Finished in 0.018564 seconds
1 example, 1 failure

Following the advice in the output, we now add the assign_role method to User.

class User
  def in_role?(role)
    true
  end

  def assign_role(role)
  end
end

$ rspec spec/user_spec.rb --format specdoc

User - should be in any roles assigned to it
Finished in 0.018998 seconds
1 example, 0 failures


Advantages :
  • Testing improves your designs: Each target object that you test must have at least two clients: your production code, and your test case. These clients force you to decouple your code
  • Testing reduces unnecessary code: When you write your test cases first, you get in the habit of writing only enough code to make the test case pass. You reduce the temptation to code features because you might need them later.

  • Simple Development Procedure:  Each test case that you write establishes a small problem. Solving that problem with code is rewarding.

  • Testing allows more freedom:  If you have test cases that will catch likely errors, you'll find that you're more willing to make improvements to your code.

  • Efficient Product: If we can generate test cases for all the possible scenarios, then the result will be highly efficient, well documented product. TDD can lead to more modularized, flexible, and extensible code.

  • Documentation: After using this technique it satisfies a bunch of requirements, also have documentation, describing the behavior of the system, and a good start at a test suite. Each test case backs up a fundamental requirement in the system

Disadvantages :
  • Big time investment. For the simple case we lose about 20+% of the actual implementation, but for complicated cases you lose much more. Also more code to write. We have to create test cases  for models,  controllers  and  views ,which consumes a lot of time
  • Additional Complexity. For complex cases test cases are harder to calculate.
  •  Design Impacts. Sometimes the design is not clear at the start and evolves as we go along - this will force us to redo the test which will generate a big time lose
  • Continuous Tweaking. For data structures and black box algorithms unit tests would be perfect, but for algorithms that tend to be changed, tweaked or fine tuned, this can cause a big time investment that one might claim is not justified.

Friday, March 16, 2012

An Intoduction into FreeBSD ports

Under Linux Platform we usually use rpm ,up2date ,yum or apt-get command to install a package.
Under FreeBSD you can use pkg_add command or ports system.

The FreeBSD Ports Collection is a package management system that provides an easy and consistent way of installing software packages on the FreeBSD. Usually ports is located at /usr/ports directory.

The FreeBSD Ports and Packages Collection offers a simple way for users and administrators to install applications. There are currently 23322 ports available.
Installing an application is as simple as downloading the port, unpacking it and typingmakein the port directory. However, the most convenient (and common) method is to download the framework for the entire list of ports by installing the entire ports hierarchy at FreeBSD installation time, and then have thousands of applications right at your fingertips.

Task: Find out FreeBSD port name or package name

There are 3 different methods available to search a port name. Use any one of the following method only.

#1 : Using whereis command

If you know the exact name of the port, but just need to find out which category it is in, you can use the whereis(1) command. Simply type whereis file, where file is the program you want to install.
# whereis php5
Output:
php5: /usr/ports/lang/php5
# whereis lighttpd
Output:
lighttpd: /usr/ports/www/lighttpd

#2: Using make command

Change directory to /usr/ports
# cd /usr/ports
To search type the command as follows:
# make search name="package-name"
For example search a package called lighttpd or php
# make search name="php"
OR
# make search name="lighttpd"
Output:
Port:   lighttpd-1.4.13_2
Path:   /usr/ports/www/lighttpd
Info:   A secure, fast, compliant, and very flexible Web Server
Maint:  mnag@FreeBSD.org
B-deps: autoconf-2.59_2 libtool-1.5.22_4 m4-1.4.8_1 pcre-7.0_1 perl-5.8.8
R-deps: pcre-7.0_1
WWW:    http://www.lighttpd.net/

#3: Using locate command

You can also use locate command:
# locate php
# locate php | grep php5

Task: Install FreeBSD port

Above output displays port Path - /usr/ports/www/lighttpd. Just change directory to /usr/ports/www/lighttpd
# cd /usr/ports/www/lighttpd
Now install a port:
# make; make install
Clean the source code tree:
# make clean
 Thanks & HAppp Porting..............!

Thursday, March 15, 2012

Installing Mysql 5.1 on FreeBSD

Now its turn for configuring MySQL

We all aware of Mysql and a lot of times it is the first things we install on a server. I recently tried it on my FreeBSD server and it went well.
You can install mysql from the FreeBSD Ports Collection.

cd /usr/ports/databases/mysql51-server make install clean

Then you will have to wait until the package builds itself from source.
* please wait it will take some time to complete...refresh  your eyes...have a chat with your friend...:)-
Once that is done you will want to use mysql’s install script to get you up and running:
/usr/local/bin/mysql_install_db
Make the mysql directory owned by the user, ’mysql’.

chown -R mysql /var/db/mysql/ chgrp -R mysql /var/db/mysql/
chown changes the user and/or group ownership of each given file, according to its first non-option argument, which is interpreted as follows. If only a user name (or numeric user ID) is given, that user is made the owner of each given file, and the files' group is not changed. If the user name is followed by a colon or dot and a group name (or numeric group ID), with no spaces between them, the group ownership of the files is changed as well. If a colon or dot but no group name follows the user name, that user is made the owner of the files and the group of the files is changed to that user's login group. If the colon or dot and group are given, but the user name is omitted, only the group of the files is changed; in this case,chownperforms the same function aschgrp.

Run mysql as the ’mysql’ user.
/usr/local/bin/mysqld_safe –user=mysql

Then you will want to set the Mysql root password:

/usr/local/bin/mysqladmin -u root password YoUrPaSSwoRd
Start Mysql on Boot
You will probably want Mysql to start on boot. To enable Mysql on boot you will need to add a line to your rc.conf file.

vi /etc/rc.conf
Then add the following lines near the bottom:

# Enable Mysql mysql_enable="YES"
Thats it! You should have a working installation of mysql and have it configured to load up on boot.

TEAMPHP: Installing Ruby on Rails in a FreeBSD Server

TEAMPHP: Installing Ruby on Rails in a FreeBSD Server: At First you have to Install ruby # pkg_add -r -v rubyusing the following command For Checking what version of Ruby installed # ru...

Installing Ruby on Rails in a FreeBSD Server


At First you have to Install ruby

# pkg_add -r -v rubyusing the following command

For Checking what version of Ruby installed
# ruby –version

* (‘#’ denotes running command as root; ‘>’ denotes running command as non privileged user).
Gems isn’t installed as default, so the next task is putting that in. A simple

“make search name=gems”

shows the gem port in /usr/ports/devel/ruby-gems.

Following the standard “make install clean” actions it will put the latest version on your machine.
#gem –version

Now you’re good to go with putting on the specific gems to get Rails apps running. We begin of course with rails itself.

# gem install  rails

This gives you a collection of gems that comprise the rails framework, and the Ruby documentation pages as well. For Installing gems you required, you can follow the below syntax.

# gem install mysql

# gem install authlogic

Rake is the Rails functionality that sets up your database schema and needs to be present for the application configuration stage.Getting that installed is done by:
# gem install rake

You Can see the list of gems installed using the command

# gem listNow we can install Apache2.2

# pkg_add -r -v apache22

Install Passenger

# pkg_add -r -v rubygem-passenger

Add lines created by running the above commands to LoadModule passenger with apache
# nano /usr/local/etc/apache2/httpd.conf
add the following lines in the httd.conf file:


LoadModule passenger_module /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.2/ext/apache2/
PassengerRoot /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.2
PassengerRuby /usr/local/bin/ruby18


*change the pasenger version as per your..

Restart apache after making changes to the configuration file for any reason, you will need to restart the server:
# /usr/local/sbin/apachectl restart


You can start the server by typing:
/usr/local/sbin/apachectl start


You can stop the server at any time by typing:
/usr/local/sbin/apachectl stop


To restart Apache without aborting current connections, run:
# /usr/local/sbin/apachectl graceful.



Now you can create and run  your ROR application ...

If You have n't installed the MySQL, then refer my next article on how to do that....

Happy COding....

Monday, May 9, 2011

Flipping of image with another using JavaScript

Below is very simple snippet code for flipping of two images using JavaScript. If possible you guys can make it generic snippet code. This code will help in mainly for showing / hiding of div’s, for example if he clicks on ‘Show Image’ it will automatically changes to ‘Hide Image’. Its a simple snippet code.


Below is the div, in div – Initially I am showing the hide image, when user clicks on this image, the image as well as the title of the img will be swapped with show image and the title will be ‘Maximize’… and Vice-Versa.

The below function should be placed in <script></script>.
//This Function is for Flipping of 'Show Image' to 'Hide Image' and Vice-Versa
function flip(imageID) {
var img = document.getElementById(imageID);
if (img.src.indexOf('images/hide.gif') > -1) {
img.src = 'images/show.gif';
img.title='Maximize';
} else {
img.src = 'images/hide.gif'
img.title='Minimize';
}
}
 below div should be placed in <body>.
<div><a href="#" onClick="flip('hide'); return false;" title="Minimize" style="padding:0px"><img src="images/hide.gif" id="hide" border="0"></a></div>

Javascript to strip special characters from a string


 <script language="JavaScript"><!--
var temp = new String('This is a te!!!!st st>ring... So??? What...');
document.write(temp + '<br>');
temp =  temp.replace(/[^a-zA-Z 0-9]+/g,'');
document.write(temp + '<br>');
//--></script>


Remove duplicates from an array using JavaScript

Here is a simple and easily understandable snippet code, to remove duplicates from an existing array using JavaScript. You guys! might have come across in some situation where in which the array has got some duplicates and want to remove those duplicates to show up unique ones. Below simple JavaScript code does the same, initially the respective array has got some value like below:

var sampleArr=new Array(1,1,1,1,1,2,2,3,3,3,4,4,4);

javascript code:

var sampleArr=new Array(1,1,1,1,1,2,2,3,3,3,4,4,4); //Declare array
document.write(uniqueArr(sampleArr)); //Print the unique value
 
//Adds new uniqueArr values to temp array
function uniqueArr(a) {
 temp = new Array();
 for(i=0;i<a.length;i++){
  if(!contains(temp, a[i])){
   temp.length+=1;
   temp[temp.length-1]=a[i];
  }
 }
 return temp;
}
 
//Will check for the Uniqueness
function contains(a, e) {
 for(j=0;j<a.length;j++)if(a[j]==e)return true;
 return false;
}

Saturday, December 4, 2010

PHP Programming Language

PHP ( Hypertext Preprocessor ) was released in the 1995PHP was originally known as Personal Home Page written as a set of Common Gateway Interface (CGI) in C Language byDanish/Greenlandic programmer Rasmus Lerdorf. Lerdorf initially created these Personal Home Page Tools to replace a small set of Perl scripts he had been using to maintain his personal homepage and was originally designed to replace a set of Perl scripts to maintain his Personal Home Pages (also known as PHP) in 1994. He combined these with his Form Interpreter to create PHP/FI, which had more functionality. PHP/FI included a larger implementation for the C programming language and could communicate with databases, enabling the building of simple, dynamic web applications. Lerdorf released PHP publicly on June 8, 1995 to accelerate bug location and improve the code.This release was named PHP version 2 and already had the basic functionality that programming php has today.
Mainly , PHP was designed to create dynamic and more interactive web pages. It is a server-side scripting language embed with HTML. Now a days , it is the most widely-used open-source and general-purpose scripting language. PHP code in a script can interect with databases, create images, read and write files and talk to remote servers. So the output from PHP code is combined with HTML in script and the result is sent to the user as a web page.

All major operating systems including LinuxMicrosoft Windows, Mac OS X, and RISC OS , you can use PHP in all these operating systems. As you know there are procedural programming or object oriented programming. PHP uses either procedural programming or object oriented programming. Also you can mix them and use both ( procedural programming or object oriented programming ). As i mention above, PHP is used mainly in server-side scripting,command line interface and writing desktop applications. PHP also supports ODBC, theOpen Database Connection standard which allows you to connect to other databasessupporting this world standard. For database , phpMyAdmin is most widely used for PHP developement. Server-side scripting is the most traditional one for PHP development. In order to use PHP for server-side scripting you need
1. PHP parser
2. Web server
3. Web browser.

The PHP codes entered with the parser on a web server will be translated into a PHP page that can be viewed on your web browser. Main reason behind popularity of PHP language is , it can be embedded directly into HTML coding. It has more benefits such as the following

1. It can be used on all major operating systems.
2. It can be supported by most of the web servers.
3. The latest version of PHP development is a very stable and grown-up language used for web programming like Java and C#.