Make unit tests great again – Integrate Jasmine into Rails


Bookmark and Share

Jasmine is a framework to write tests for the Javascript code in the Behaviour Driven Development (BDD) style. In this article, you will learn how to integrate Jasmine into your existing rails application and how to write clean and beautiful unit tests. Let us make tests great again!

 

Install Jasmine

To make Jasmine available to your Rails app, you just have to place the jasmine-gem (link) in your Gemfile. That will do the magic. Just make sure you have it under Development and Test group in the Gemfile as follows:

Then run this to install the gem:

After all the gems are installed, run this code to generate necessary files for Jasmine to run:

This will create the jasmine helper file and the yml file where you configure how it should run the tests.

Run tests

You can use Jasmine right after it’s installed. It can be run in several ways, the most important ones being,

  • In your browser
  • Continuous Integration Mode (CI)
  • The CI mode is usually used when you have to integrate it into your build system.

    Browser Mode

    You have to start the Jasmine server to run it in a browser. This server runs all the tests and serves the results to a webpage. …

    Read More

    Taking screenshots of webpages using Ruby


    Bookmark and Share

    Recently we have been working on taking screenshots for web page while generating reports based on that website. During this endeavor, we came across some tools to achieve that. We are sharing the information we gathered here.

    The tools that we will discuss for screencapture, in  Ruby,  are:

    • PhantomJS
    • Screencap gem
    • Webshot gem

    Screencap and webshot are gems in Ruby that depends on a tool called PhantomJS. It is basically a web browser without a user interface, primarily used for testing websites. Such type of browsers are generally referred to as headless browsers,

    Screenshots with PhantomJS

    PhantomJS is quite easy to install and is multiplatform, available on major operating systems.

    To start, our script must require a reference to the webpage module then use it to create an instance:

    Use the instance.open() method and pass it the arguments, the url of the webpage that we want to capture screenshot.

    instance.render() method captures the screenshot and saves it to the file specified in the argument.
    Run the script as,

    Screenshot is saved in the  directory where we run the script.

    Now what we have above is all JavaScript, but to use the phantom JS in our rails application we have gems that provide us with an easy interface to acheive the …

    Read More

    Rack::Attack – secure you rails app for the real world


    Bookmark and Share

    Are you worried about the security issues in your Rails app? The rack-attack gem, can help you. Rack::Attack is a rack middleware which provides security to our rails application. It allows us to safelist, blacklist, throttle and to track requests.

    • If the request matches any safelist, it is allowed.
    • If the request matches any blocklist, it is blocked.
    • If the request matches any throttle, a counter is incremented in the Rack::Attack.cache. If any throttle’s limit is exceeded, the request is blocked.
    • Otherwise, all tracks are checked, and the request is allowed.

    Implementation

    Install the rack-attack gem, or add it to you Gemfile as:

    Then tell your app to use the Rack::Attack middleware. For Rails 3+ apps:

    Or you can use it in Rackup file as

    By default, Rack Attack uses Rails cache. You can override that by setting the Rack::Attack.cache.store value. It is used for throttling. If you want to create use a custom adapter, for example, memory store,  create a file called rack_attack.rb in config/initializers to configure Rack Attack and put the following code in the file:

    Throttle

    Here we are limiting the request per seconds from the same IP address. Here we are limiting only 3 requests in 10 sec.

    Safelist

    Above example always …

    Read More

    Chartkick: data visualization made easy with Ruby


    Bookmark and Share

    Recently, I’ve been using Highcharts, Google charts and Chart Js for visualizing dynamic data in my projects. But it was difficult to integrate it with the rails application. However, for every problem in Ruby, there is a gem out there to save your day and Chartkick, a Ruby gem exclusively available for data visualization is truly a savior. Chartkick can work with Highcharts, Chart.js and Google charts to create dynamic and interactive charts that draw data from the Rails application. And the best part, you just need to write one single line of Ruby code. Isn’t that amazing and powerful!

    Let’s begin with Installation

    For installation, all you have to do is adding this line to your application’s Gemfile:

    Then you have to choose your charting library.
    In case, if more than one charting library is loaded, choose between them with the following code:

    P.S:- highcharts is the default adapter is nothing else is defined.

    Using Chartkick

    Once it’s installed, you can start playing around with chartkick. For example:

    In the above example, I have just shown you how we can make a line chart.Similarly, you can create Pie chart, Column chart, Bar chart, Area chart, Scatter chart, Geo charts, Timeline(Google …

    Read More

    Introduction to generating JSON using PostgreSQL


    Bookmark and Share

    Introduction

    One of the major requirements for any online business is to have a backend that either provides or can be extended to provide an API response. Building  websites with static HTML and simple jquery ajax is coming to an end. In this era, Javascript frameworks rules the market. Hence, it is a good decision for the database to support JSON, as JSON is becoming the glue that connects the frontend and backend.

    Rails have an inbuilt support for generating JSON, as it’s our swiss army knife of web development, and encourages the REST URL structure . And its a good choice for building API. It is good enough to a particular point of growth. Very soon you will reach bottlenecks, where you have more requests than you can handle and you have to either spawn up more servers or use some concurrent languages like elixir, go, etc. Before we go to that scale and burn down the existing codebase, we can use database to generate JSON responses for us, which is 10 times faster in generating JSON than Rails (though more verbose).

    Since PostgreSQL 9.2, the database has taken a major leap in supporting JSON. The …

    Read More

    Lazy enumerator to handle huge files


    Bookmark and Share

    Lazy evaluation, or call-by-need is an evaluation strategy which delays the evaluation of an expression until its value is needed. It’s frequently seen in functional languages, ruby introduced the lazy method in Ruby 2.0. For those who don’t know what are enumerators: enumerators are something that can be counted. So a collection of elements, files (file is an collection of lines of string), etc can be treated as an enumerator.

    In ruby we need to make something countable into an enumerator object, which is done by applying .each and .map on it.

    Ruby has a wide range of operations we can do over a collection, it’s one of those features that makes Ruby such a powerful dynamic language. An enumerator can be used to generate series like the Fibonacci series.

    But when we do a .map / .each with a code block, then it would try to realize the enumerator fully and then apply the block over it.

    That would be fine when we are working on something small like:

    But when we take the above fib enumerator, which will grow into an infinite series, adding a .map would lead the code to an infinite loop. If you are crazy enough to write an infinite loop, …

    Read More

    Optimising PostgreSQL database query using indexes


    Bookmark and Share

    At Red Panthers PostgreSQL is our go to database we use it everywhere. So thinking about how to optimize our database performance is one of the most talked about topic at our office. The best way to speed up report generation and data retrieval within a rails application is to leave it to the database, as they have algorithms and optimizations build just for that. We always felt that most Ruby on Rails projects out there, do not use the full potential of a database and they usually just limit it to a data store. PostgreSQL or any database for that matter is much more than that.

    We would be blogging on how we use PostgreSQL in our projects to speed up our client’s applications. This particle is the first part of a series of article we would be writing on database optimization.

    Database Indexes:

    Indexes are a special lookup table that the database search engine can use to speed up data retrieval. An Index is similar to a pointer to a particular row of a table. As a real world example, consider a Britannica Encyclopedia with 22 volumes of books, and an extra book listing  the index,with which you can find out the …

    Read More

    Working with timezones in rails


    Bookmark and Share

    Ruby on Rails being an amazing framework, helps us manage the timezone of our rails application. It gives us access to a lot of helpers, to make our life easier. For example, if you want to change all the date and time of your application to the logged in users time zone, we just have to place the following code in the application_controller.

    We assume that you have stored the user’s time_zone in your database in the time_zone column.

    The application  to show  timezone can be set in your application.rb, if we don’t set a particular timezone then the application will just show the systems timezone.

    If you want to know all the timezone options available in rails, run the rake -D time command in your terminal.

    Even though rails would take care of the timezone, when we are using certain ruby commands, it gives us our systems timezone and not the one set by rails. So to avoid surprises, we should be aware of the timezones we are exposed to.

    A rails app, would always be exposed to three timezones:

    • System timezone
    • Database timezone
    • Rails applications own timezone

    All three could be different, for example your system timezone could be in …

    Read More

    after_create vs after_save vs after_commit

    after_save, after_create and after_commit are called active record call backs in rails. They get executed when we work on the database, similarly we also have before_* callback and callbacks on destroy as well. In this article I will explain you about the difference between *_save, *_create and *_commit callbacks.

    The purpose of each as per rails docs:

    after_create
    Is called after Base.save on new objects that haven‘t been saved yet (no record exists)

    after_save
    Is called after Base.save (regardless of whether it‘s a create or update save)

    after_commit
    Is called after the database transaction is completed.

    Now to explain the real difference between the three, we must first explain about database transaction. They are a protective block around a group of sql statements, that are permanent only if all of them succeed in a single atomic statement.

    When rails execute a create, the after_save and after_create would be called within the transaction block of the create statement. So they will be executed before executing the sql statement to make permanent changes in the DB. If the query fails, then no change will happen to the DB, but we would have executed the instructions of the after_create and after_save block.

    Where as after_commit, is called after the execution of the final/outer transaction block. Thus the changes in the DB would be permanent.

    Read More

    How to learn Ruby on Rails


    Bookmark and Share

    Well I have been hearing a lot from people in facebook, google groups and online forum wanting to learn Rails. Their question is simple “I want to learn Rails”, “How do I learn Ruby on Rails?”, “How do I become a Ruby on Rails programmer?”. Well the funny feeling I get while reading these questions is that, its the exact questions I posted in Google Groups, forums, etc when I wanted to start learning Rails and Ruby couple of years ago. So I thought of giving back to the community and to my company blog, by posting on how to learn rails, and answer a few questions every newbie always have.

    Q) How to learn Ruby on Rails?

    Well to get started, I would suggest this Rails Tutorial. Excellent tutorial, with detailed explanation. Build for people with little or no knowledge in Ruby. Further more it also teaches and introduces a newbie to Git and TDD.

    If you don’t like reading from the web, and prefer books then I suggest Agile Web Development With Rails by Sam Ruby, Dave Thomas, David Heinemeier Hansson. The advantage of using rails is the ability to become more …

    Read More