Tuesday 9 August 2016

Active Jobs

Active job is a rails framework for running background jobs, It's included as rails component as same like other components like active record, Active model etc

What is Background Jobs and why do we need?
You’re always striving to give your users a better experience when they use your website or application, 

One of the most important ways to achieve this is by giving them quick server response times and processing the non web responses in the background like Email, Payments, sms, Data processing, Video, audio upload etc..


  • Active Job was first included in Rails 4.2
  • Why to use Active Job instead of directly using Third party Background processing
  • Gives the common place to write the jobs
  • We will be able to switch between the queuing backend without having to rewrite the jobs just by changing the queue and backend processing table.
  • Active Job allows your Rails app to work with any one of the backend queue through a single standard interface

  • Even if you aren’t ready to use a queue in your application, you can still use Active Job with the default Active Job Inline backend Jobs enqueued with the Inline adapter get executed immediately.

Active Job adapters Backends Features


|                   | Async | Queues | Delayed    | Priorities | Timeout | Retries |
|-------------------|-------|--------|------------|------------|---------|---------|
| Backburner        | Yes   | Yes    | Yes        | Yes        | Job     | Global  |
| Delayed Job       | Yes   | Yes    | Yes        | Job        | Global  | Global  |
| Qu                | Yes   | Yes    | No         | No         | No      | Global  |
| Que               | Yes   | Yes    | Yes        | Job        | No      | Job     |
| queue_classic     | Yes   | Yes    | Yes*       | No         | No      | No      |
| Resque            | Yes   | Yes    | Yes (Gem)  | Queue      | Global  | Yes     |
| Sidekiq           | Yes   | Yes    | Yes        | Queue      | No      | Job     |
| Sneakers          | Yes   | Yes    | No         | Queue      | Queue   | No      |
| Sucker Punch      | Yes   | Yes    | Yes        | No         | No      | No      |
| Active Job Async  | Yes   | Yes    | Yes        | No         | No      | No      |
| Active Job Inline | No    | Yes    | N/A        | N/A        | N/A     | N/A     |

Resque and delayed Job

  1. Resque supports multiple queues
  2. DelayedJob supports numeric priorities
  3. Resque workers are resilient to memory leaks
  4. DelayedJob workers are extremely simple and easy to modify
  5. Resque requires Redis
  6. DelayedJob requires ActiveRecord
  7. Resque can only place JSONable Ruby objects on a queue as arguments
  8. DelayedJob can place any Ruby object on its queue as arguments
  9. Resque includes a Sinatra app for monitoring what's going on
  10. DelayedJob can be queried from within your Rails app if you want to add an interface

A. Generating a job
     Active Job provides a Rails generator to create jobs
     rails generate job site_subscription_payment
B. Enqueue the Job
    SiteSubscriptionPaymentJob.perform_later subscription_obj
    SiteSubscriptionPaymentJob.set(wait_until:         Date.tomorrow.noon).perform_later(subscription_obj)
    SiteSubscriptionPaymentJob.set(wait: 1.week).perform_later(subscription_obj)
    SiteSubscriptionPaymentJob.perform_later(subscription_obj, company)
C. Job Execution
For enqueuing and executing jobs in production we need to set up a queuing backend Rails itself only provides an in-process queuing system, which only keeps the jobs in RAM. If the process crashes or the machine is reset, then all outstanding jobs are lost with the default async back-end
D. Setting the Backend  config/application.rb
config.active_job.queue_adapter = :delayed_job
E. Starting the Backend
Since jobs run in parallel to your Rails application, most queuing libraries require that you start a library-specific queuing service (in addition to starting your Rails app) for the job processing to work
F. Queues
MyJob.set(queue: :another_queue).perform_later(record)
queue_as :low_priority
Callbacks

Active Job provides hooks during the life cycle of a job. Callbacks allow you to trigger logic during the life cycle of a job.

A. Available callbacks
before_enqueue
around_enqueue
after_enqueue
before_perform
around_perform
after_perform

 before_enqueue do |job|
    # Do something with the job instance
  end

  around_perform do |job, block|
    # Do something before perform
    block.call
    # Do something after perform
  end

Action Mailer
One of the most common jobs in a modern web application is sending emails outside of the request-response cycle
So the user doesn't have to wait on it. Active Job is integrated with Action Mailer so you can easily send emails asynchronously

# If you want to send the email now use #deliver_now
ApplicationNotifier.user_approved(@user).deliver_now

# If you want to send the email through Active Job use #deliver_later
ApplicationNotifier.user_approved(@user).deliver_later






Tuesday 2 February 2016

Automation Testing Using Rspec and Cucumber In Ruby on Rails

Automation Testing:

1. Unit Test

A unit test focuses on a single “unit of code” – usually a function in an object or module. By making the test specific to a single function, the test should be simple, quick to write, and quick to run. This means you can have many unit tests, and more unit tests means more bugs caught. They are especially helpful if you need to change your code, as you can safely do so and trust that any other code will not break.

2. Integration Test

Multiple pieces are tested together, for example testing database access code against a test database

3. Acceptance test/ Function Test/Automation Test

Automatic testing of the entire application End to End Testing or "Full Application", for example using a tool like Selenium to automatically run a browser.

TDD - Test Driven Development

a. Write Test
b. Write code
c. Run Test
d. Clean up code

Red, Green, Refactor

BDD - Behavior Driven Development

Difference Between TDD and BDD

BDD uses a more verbose style so that it can be read almost like a sentence. BDD is to test the TDD

  1. BDD focuses on the behavioural aspect of the system rather than the implementation aspect of the system that TDD focuses on.
  2. BDD gives a clearer understanding as to what the system should do from the perspective of the developer and the customer. TDD only gives the developer an understanding of what the system should do.
  3. BDD allows both the developer and the customer to work together to on requirements analysis that is contained within the source code of the system.

Webdriver

WebDriver is a tool for writing automated tests of websites. It aims to mimic the behaviour of a real user, and as such interacts with the HTML of the application.

Capybara uses the same DSL to drive a variety of browser and headless drivers
Rack_test
RackTest is Capybara's default driver.
It is written in pure Ruby and does not have any support for executing JavaScript.
Since the RackTest driver interacts directly with Rack interfaces, it does not require a server to be started
If your application is not a Rack application (Rails, Sinatra and most other Ruby frameworks are Rack applications) then you cannot use this driver
you cannot use the RackTest driver to test a remote application, or to access remote URLs (e.g., redirects to external sites, external APIs, or OAuth services)

Selenium
Capybara-webkit
Poltergeist

Rspec

Rspec is a Testing Framework, Rspec stands for Ruby Specification. Rspec is a low level testing, Rspec is very good for unit testing, that is testing models, controllers, views.


Add below code into your gemfile and bundle install or install it by command line
group :development, :test do
  gem 'rspec-rails', '~> 2.0'
end
Or  gem install rspec-rails

Create the Basic Skelton
rails generate rspec:install

Create the RSpec binstub. In short, the binstub will allow you to run RSpec with bin/rspec instead of bundle exec rspec
bundle binstubs rspec-core

Cucumber 
Cucumber is a high-level testing framework which is designed to let you use Behaviour Driven Development (BDD) to create Ruby on Rails applications
Cucumber’s unique feature is that it uses English (or a number of other supported languages) to define an application’s behaviour.
Gherkin is the language that Cucumber understands
It is a Business Readable, Domain Specific Language that lets you describe software’s behaviour withIt Uses the struout detailing how that behaviour is implemented

Feature file consists of the scenario
Step definition consists of the ruby code to pass the scenario


shoulda-matchers

shoulda-matchers lets us spec common Rails functionality, like validations and associations, with less code.
gem 'shoulda-matchers'
bundle install
should validate_presence_of(:firstname)
http://matchers.shoulda.io/docs/v3.1.1/




Factory-Girl

factory_girl is a fixtures replacement with a straightforward definition syntax(i.e Test data)
gem 'factory_girl' and bundle install
Create the directory called factories and define with the filename same as table name
FactoryGirl.define do
  factory :user do
    firstname "satheesh"
    lastname "kumar"
    email "satheeshkumark@gmail.com"
    password "password"
  end
end

@user = FactoryGirl.build(:user)