Sunday, September 18, 2016

Difference between a class and a module

╔═══════════════╦═══════════════════════════╦═════════════════════════════════╗
║               ║ class                     ║ module                          ║
╠═══════════════╬═══════════════════════════╬═════════════════════════════════╣
║ instantiation ║ can be instantiated       ║ can *not* be instantiated       ║
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
║ usage         ║ object creation           ║ mixin facility. provide         ║
║               ║                           ║   a namespace.                  ║
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
║ superclass    ║ module                    ║ object                          ║
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
║ methods       ║ class methods and         ║ module methods and              ║
║               ║   instance methods        ║   instance methods              ║
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
║ inheritance   ║ inherits behaviour and can║ No inheritance                  ║
║               ║   be base for inheritance ║                                 ║
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
║ inclusion     ║ cannot be included        ║ can be included in classes and  ║
║               ║                           ║   modules by using the include  ║
║               ║                           ║   command (includes all         ║
║               ║                           ║   instance methods as instance  ║
║               ║                           ║   methods in a class/module)    ║
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
║ extension     ║ can not extend with       ║ module can extend instance by   ║
║               ║   extend command          ║   using extend command (extends ║
║               ║   (only with inheritance) ║   given instance with singleton ║
║               ║                           ║   methods from module)          ║
╚═══════════════╩═══════════════════════════╩═════════════════════════════════

Difference between rspec, capybara and cucumber

rspec is a full-featured testing framework that will let you write what Rails considers unit tests, functional tests, and integration tests. All of these exercise Ruby code through various layers of your Rails application. All of these tests simulate requests to your Rails application, but don't actually run the application end-to-end over the network.

cucumber is a browser based integration testing framework, which allows writing automated tests that run against the entire Rails application accessed from within an automated web browser. This allows you to write automated tests about in-browser behavior for JS or CSS. Cucumber provides a unique angle on integration testing that uses plain english specification mapped to code via regular expressions. This allows a more natural "Behavior Driven Development" model - describing what a web application should do, in plain language, from the perspective of the user.

capybara is a particular web driver powering the cucumber integration testing framework, that uses headless webkit. This allows running a headless (without UI) Chrome/Webkit browser for automated testing. This is very useful both in development, but especially on a remote test/continuous integration server.

So rspec and cucumber are similar in being testing frameworks with their own way of specifying things. rspec has a nice DSL that's very readable while being actual code. cucumber maps plain text descriptions to real code.

Though cucumber is usually used on top of capybara, you can also use rspec to drive capybara integration tests. The tests are written in either rspec or cucumber, but capybara is an integration engine underneath.


RSpec and Cucumber are both testing frameworks. RSpec includes traditional Unit Testing (which means testing a class or part of the application in isolation from the rest of the application. So your model does what your model is supposed to do, the controller does what it is supposed to do, etc).

RSpec and Cucumber both are used for Acceptance Testing (Which is called ATDD, BDD, Specification by Example, etc depending on who you ask). These are business-case driven Integration Tests, which mean they simulate the way a user uses the application and uses the full Rails stack so problems with the way the different parts of your application work together can be found in a way that unit testing will not find.

The main difference between RSpec and Cucumber are the business readability factor. Cucumber's main draw is that the specification (features) are separate from the test code, so your product owners can provide or review the specification without having to dig through code. These are the .feature files that you make in Cucumber. RSpec has a similar mechanism, but instead you describe a step with a Describe, Context or It block that contains the business specification, and then immediately have the code that executes that statement. This approach is a little easier for developers to work with but a little harder for non-technical folks.

Which to use? If you are the sole developer and product owner, then I would stick with RSpec, I feel it's easier to a technical person to understand, offers a few advantages in keeping things scoped and under control, and keep you out of messing with RegExs for test steps. If you are building this for a client, and they are hands-on with regard to the Specification, go with Cucumber for your Acceptance Test and use RSpec for Unit Tests.

Just to demonstrate the main difference between the two:

Cucumber:

#articles.feature
Given an article exists called "Testing Demonstration"
When I visit the list of articles
Then I should see an article called "Testing Demonstration"

#article_steps.rb
Given /^an article exists called "(.+)"$/ do |title|
  FactoryGirl.create(:article, title: title)
end
When /^I visit the list of articles$/ do
  visit articles_path
end
Then /^I should see an article called "(.+)"$/ do |title|
  page.should have_content title
end

Rspec

describe "Articles" do
  let(:article) { FactoryGirl.create(:article) }
  context "Index Page" do
    before { visit articles_path }
    it { page.should have_content article.title }
  end
end



Capybara is a tool that interacts with a website the way a human would (like visiting a url, clicking a link, typing text into a form and submitting it). It is used to emulate a user's flow through a website. With Capybara you can write something like this:

describe "the signup process", :type => :feature do
  before :each do
    User.make(:email => 'user@example.com', :password => 'caplin')
  end

  it "signs me in" do
    visit '/sessions/new'
    within("#session") do
      fill_in 'Login', :with => 'user@example.com'
      fill_in 'Password', :with => 'password'
    end
    click_link 'Sign in'
    page.should have_content 'Success'
  end
end

Cucumber is a tool to write human-readable tests that are mapped into code. With it, you can rewrite the above example like this:

Scenario: Signup process

Given a user exists with email "user@example.com" and password "caplin"
When I try to login with "user@example.com" and "caplin"
Then I should be logged in successfully

The almost plain-text interpretation is useful to pass around non-developers but also need some code mapped into it to actually work (the step definitions).

Usually you will use Capybara if you're testing a website and use Cucumber if you need to share those tests with non-developers. These two conditions are independent so you can use one without the other or both or none.

PS: in the code snippet there is some RSpec as well. This is needed because Cucumber or Capybara by themselves cannot test something. They rely on RSpec, Test::Unit or minitest to do the actual "Pass or Fail" work.

Preload, Eagerload, Includes and Joins

Rails provides four different ways to load association data. In this blog we are going to look at each of those.

Preload

Preload loads the association data in a separate query.
User.preload(:posts).to_a

# =>
SELECT "users".* FROM "users"
SELECT "posts".* FROM "posts"  WHERE "posts"."user_id" IN (1)
This is how includes loads data in the default case.
Since preload always generates two sql we can’t use posts table in where condition. Following query will result in an error.
User.preload(:posts).where("posts.desc='ruby is awesome'")

# =>
SQLite3::SQLException: no such column: posts.desc:
SELECT "users".* FROM "users"  WHERE (posts.desc='ruby is awesome')
With preload where clauses can be applied.
User.preload(:posts).where("users.name='Neeraj'")

# =>
SELECT "users".* FROM "users"  WHERE (users.name='Neeraj')
SELECT "posts".* FROM "posts"  WHERE "posts"."user_id" IN (3)

Includes

Includes loads the association data in a separate query just like preload.
However it is smarter than preload. Above we saw that preload failed for query User.preload(:posts).where("posts.desc='ruby is awesome'"). Let’s try same with includes.
User.includes(:posts).where('posts.desc = "ruby is awesome"').to_a

# =>
SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, "posts"."id" AS t1_r0,
       "posts"."title" AS t1_r1,
       "posts"."user_id" AS t1_r2, "posts"."desc" AS t1_r3
FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" = "users"."id"
WHERE (posts.desc = "ruby is awesome")
As you can see includes switches from using two separate queries to creating a single LEFT OUTER JOIN to get the data. And it also applied the supplied condition.
So includes changes from two queries to a single query in some cases. By default for a simple case it will use two queries. Let’s say that for some reason you want to force a simple includes case to use a single query instead of two. Use references to achieve that.
User.includes(:posts).references(:posts).to_a

# =>
SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, "posts"."id" AS t1_r0,
       "posts"."title" AS t1_r1,
       "posts"."user_id" AS t1_r2, "posts"."desc" AS t1_r3
FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" = "users"."id"
In the above case a single query was done.

Eager load

eager loading loads all association in a single query using LEFT OUTER JOIN.
User.eager_load(:posts).to_a

# =>
SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, "posts"."id" AS t1_r0,
       "posts"."title" AS t1_r1, "posts"."user_id" AS t1_r2, "posts"."desc" AS t1_r3
FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" = "users"."id"
This is exactly what includes does when it is forced to make a single query when where or order clause is using an attribute from posts table.

Joins

Joins brings association data using inner join.
User.joins(:posts)

# =>
SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
In the above case no posts data is selected. Above query can also produce duplicate result. To see it let’s create some sample data.
def self.setup
  User.delete_all
  Post.delete_all

  u = User.create name: 'Neeraj'
  u.posts.create! title: 'ruby', desc: 'ruby is awesome'
  u.posts.create! title: 'rails', desc: 'rails is awesome'
  u.posts.create! title: 'JavaScript', desc: 'JavaScript is awesome'

  u = User.create name: 'Neil'
  u.posts.create! title: 'JavaScript', desc: 'Javascript is awesome'

  u = User.create name: 'Trisha'
end
With the above sample data if we execute User.joins(:posts) then this is the result we get
#<User id: 9, name: "Neeraj">
#<User id: 9, name: "Neeraj">
#<User id: 9, name: "Neeraj">
#<User id: 10, name: "Neil">
We can avoid the duplication by using distinct .
User.joins(:posts).select('distinct users.*').to_a
Also if we want to make use of attributes from posts table then we need to select them.
records = User.joins(:posts).select('distinct users.*, posts.title as posts_title').to_a
records.each do |user|
  puts user.name
  puts user.posts_title
end
Note that using joins means if you use user.posts then another query will be performed.

Apache Interview Questions

1) How to check the version of Apache server ?

Ans: # httpd -v

2) What is meaning of “Listen” in httpd.conf file ?

Ans: Port number on which to listen for nonsecure (http) transfers.

3) If you specify both deny from all and allow from all, what will be the default action of Apache?

Ans: Deny always takes precedence over allow.

4) What is DocumentRoot ?

Ans: The document root is a directory that is designated for holding web pages. By default, the Apache HTTP server is configured to serve files from the /var/www/html/ directory.

5) Tell me name of main configuration file of Apache server ?

Ans: /etc/httpd/conf/httpd.conf

6)Does Apache act as Proxy server?

Ans:Yes,using mod_proxy module.

7) What do you mean by a ServerName directive?

Ans: The DNS system is used to associate IP addresses with domain names. The value of ServerName is returned when the server generates a URL. If you are using a certain domain name, you must make sure that it is included in your DNS system and will be available to clients visiting your site.

8) What is the main difference between and sections?

Ans: Directory sections refer to file system objects; Location sections refer to elements in the address bar of the Web page

9) What is the difference between a restart and a graceful restart of a web server?

Ans: During a normal restart, the server is stopped and then started, causing some requests to be lost. A graceful restart allows Apache children to continue to server their current requests until they can be replaced with children running the new configuration.

10) What is the difference between ServerName directive and ServerAlias?

Ans: ServerName directive is hostname and port that the server uses to identify itself and ServerAlias is alternate names for a host used when matching requests to name-virtual hosts.

11) How t to enable PHP scripts on your server?

Ans: If you have mod_php installed, use AddHandler.
AddHandler application/x-httpd-php .phtml .php

12) How to enable htaccess on Apache?

Ans:
Open httpd.conf and remove the comment on line from

;LoadModule rewrite_module modules/mod_rewrite.so

Find the following
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all

Replace it
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
allow from all

13) What is ServerType directive?

Ans: It defines whether Apache should spawn itself as a child process (standalone) or keep everything in a single process (inetd). Keeping it inetd conserves resources. This is deprecated, however.

14) What is mod_vhost_alias?

Ans: It allows hosting multiple sites on the same server via simpler configurations.

15) Which tool you have used for Apache benchmarking?

Ans: ab (Apache bench) ab -n 1000 -c 10 http://www.techoism.com/launch-an-amazon-ec2-instance/

16) How you will put a limit on uploads on your web server?

Ans: This can be achieved be LimitRequestBody directive.
<Directory "/usr/local/apache2/htdoc/wp-content/uploads">
LimitRequestBody 100000
<Directory>
Here I have put limit of 100000 Bytes

17) I want to stop people using my site by Proxy server. Is it possible>

Ans:
<Directory "proxy:http://www.techoism.com/content">
Order Allow,Deny
Satisfy All
<Directory>

18) What we can do to find out how people are reaching your site?

Ans: Add the following effector to your activity log format.%{Referer}

19) If you have added “loglevel debug” in htpd.conf file, than what will happen?

Ans: It will give you more information in the error log in order to debug a problem.

20) How to check for the httpd.conf consistency and any errors in it?

Ans: httpd -t

Nginx Interview Questions

1) Explain what is Nginx?

Nginx is a web server and a reverse proxy server for HTTP, HTTPS, SMTP, POP3 and IMAP protocols.

2) Mention some special features of Nginx?

Special features of the Nginx server includes

    Reverse proxy/ L7 Load Balancer
    Embedded Perl interpreter
    On the fly binary upgrade
    Useful for re-writing URLs and awesome PCRE support

3) Mention what is the difference between Nginx and Apache?
   
   #Nginx                                    

    Nginx is an event based web server
    All request are handled by a single thread.
    Nginx avoids child processes idea.
    Nginx resembles speed
    Nginx is better when it comes to memory consumption and connection
    Nginx is better when you want load-balancing
    For PHP, Nginx might be preferable as it supports PHP internally
    Nginx do not support O.S like IBMi and OpenVMS.
    Nginx comes only with core features
    Nginx performance and scalability do not depend on hardware

   
    #Apache
     Apache is a process based server
    Single thread handles a single request.
    Apache is based on child processes
    Apache resemble power
    Apache is not up-to the mark when it comes to memory consumption and connection
    Apache will refuse new connections when traffic reaches the limit of processes
    Apache support’s PHP, Python, Perl and other languages using plugins. It is useful when application is based on Python or Ruby
    Apache support much wider range of O.S
    Apache provides lot more functionality than Nginx
    Apache is dependent on hardware components like CPU and memory

4) Explain how Nginx can handle HTTP requests?

Nginx uses the reactor pattern.  The main event loop waits for the OS to signal a readiness event- such that the data is accessible to read from a socket, at which instance it is read into the buffer and processed.  A Single thread can serve tens of thousands of simultaneous connections.

5) In Nginx how you can prevent processing requests with undefined server names?

A server that just drops the requests can be defined as



Server {

listen                80;

server_name  “ “ ;

return              444;

}

Here the server name is kept as an empty string which will match request without the “Host” header field, and a special Nginx’s non-standard code 444 is returned that terminates the connection.

Nginx-logo

6) What is the advantage of using a “reverse proxy server”?

The reverse proxy server can hide the presence and characteristics of the origin server. It acts as an intermediate between internet cloud and web server. It is good for security reason especially when you are using web hosting services.

7) Mention what is the best usage of Nginx server?

The best usage of Nginx server is to deploy dynamic HTTP content on a network with using SCGI, WSGI application servers, FastCGI handlers for scripts.  It can also serve as a load balancer.

8) Mention what is the Master and Worker Processes in Nginx Server?

    Worker processes: It reads and evaluate configuration and maintain worker processes.
    Master processes: It actually does the processing of the requests.

9) Explain how you can start Nginx through a different port other than 80?

To start Nginx through a different port, you have to go to /etc/Nginx/sites-enabled/ and if this is the default file, then you have to open file called “default.” Edit the file and put the port you want

Like server { listen 81; }

10) Explain is it possible to replace Nginx errors like 502 error with 503?

    502= Bad gateway
    503= Server overloaded

Yes, it is possible but you to ensure that fastcgi_intercept_errors is set to ON, and use the error page directive.



Location / {

fastcgi_pass 127.0.01:9001;

fastcgi_intercept_errors on;

error_page 502 =503/error_page.html;

#…

}

11) In Nginx, explain how you can keep double slashes in URLs?

To keep double slashes in URLs you have to use merge_slashes_off;

Syntax: merge_slashes [on/off]

Default: merge_slashes on

Context: http, server

12) Explain what is ngx_http_upstream_module is used for?

The ngx_http_upstream_module is used to define groups of servers that can reference by the fastcgi pass, proxy pass, uwsgi pass, memcached pass and scgi pass directives.

13) Explain what is C10K problem?

C10K problem is referred for the network socket unable to handle a large number of client (10,000) at the same time.

14) Mention what is the use of stub_status and sub_filter directives?

    Stub_status directive: This directive is used to know the current status of Nginx like current active connection, total connection accepted and handled current number of read/write/wait connection
    Sub_filter directive: It is used to search and replace the content in response, and quick fix for stale data

15) Explain does Nginx support compress the request to the upstream?

You can compress the request to the upstream by using the Nginx module gunzip. The gunzip module is a filter that decompresses responses with “Content Encoding: gzip” for clients or servers that do not support “gzip” encoding method.

16) Explain how you can get the current time in Nginx?

To get the current time in Nginx, you have to use variables from SSI module, $date_gmt and $date_local.

    Proxy_set_header THE-TIME $date_gmt;

17) Explain what is the purpose of –s with Nginx Server?

To run the executable file of Nginx –s parameter is used.

18) Explain how to add modules in Nginx Server?

During the compilation process, Nginx modules must be selected as such run-time selection of modules is not supported by Nginx.

Cucumber Interview Questions

Cucumber – a Behavior Driven Development (BDD) framework which is used with Selenium for performing acceptance testing.

Cucumber Introduction:

Cucumber is a tool based on Behavior Driven Development (BDD) framework which is used to write acceptance tests for web application. It allows automation of functional validation in easily readable and understandable format (like plain English) to Business Analysts, Developers, Testers, etc.
Cucumber feature files can serve as a good document for all. There are many other tools like JBehave which also support BDD framework. Initially Cucumber was implemented in Ruby and then extended to Java framework. Both the tools support native JUnit.
Behavior Driven Development is extension of Test Driven Development and it is used to test the system rather than testing the particular piece of code. We will discuss more about the BDD and style of writing BDD tests.
Cucumber can be used along with Selenium, Watir, and Capybara etc. Cucumber supports many other languages like Perl, PHP, Python, .Net etc. In this tutorial we will concentrate on Cucumber with Java as a language.

Cucumber Basics:

In order to understand cucumber we need to know all the features of cucumber and its usage.
#1) Feature Files:
Feature files are essential part of cucumber which is used to write test automation steps or acceptance tests. This can be used as live document. The steps are the application specification. All the feature files ends with .feature extension.
Sample feature file:
Feature: Login Functionality Feature
In order to ensure Login Functionality works,
I want to run the cucumber test to verify it is working
Scenario: Login Functionality
Given user navigates to SOFTWARETETINGHELP.COM
When user logs in using Username as “USER” and Password “PASSWORD”
Then login should be successful
Scenario: Login Functionality
Given user navigates to SOFTWARETETINGHELP.COM
When user logs in using Username as “USER1” and Password “PASSWORD1”
Then error message should be thrown


 ============================================

1) What is Cucumber and what are the advantages of Cucumber?

To run functional tests written in a plain text Cucumber tool is used. It is written in a Ruby programming language.

Advantages of Cucumber

    You can inolve business stakeholders who can not code
    End user experience is priority
    High code reuse

2) What are the 2 files required to execute a Cucumber test scenario?

The 2 files required to execute a Cucumber test scenario are

    Features
    Step Definition

3) What is feature file in Cucumber? What does feature file consist of ?

Feature file in cucumber consist of parameters or conditions required for executing code, they are

    Feature
    Scenario
    Scenario Outline
    Given
    When
    Then

4) Give an example of behaviour driven test in plain text?

    Feature: Visit XYZ page in abc.com
    Scenario : Visit abc.com
    Given:  I am on abc.com
    When:  I click on XYZ page
    Then:  I should see ABC page

5) Explain what is Scenario Outline in feature file?

Scenario Outline:  Same scenario can be executed for multiple sets of data using scenario outline.  The data is provided by a tabular structure separated by (I   I).

6) What is step definition in Cucumber?

A step definition is the actual code implementation of the feature mentioned in feature file.

061114_1018_Introductio1

7) Give the example for step definition using “Given” function?

For example to make visitor visit the site “Yahoo” the command we use for given

Given (/^ I am on www.yahoo.com$/) do

Browser.goto “http://www.yahoo.com”

end – This will visit www.yahoo.com

8) What are the difference between Jbehave and Cucumber?

Although Cucumber and Jbehave are meant for the same purpose, acceptance tests are completely different frameworks

    Jbehave is Java based and Cucumber is Ruby based
    Jbehave are based on stories while Cucumber is based on features

9) Explain what is test harness?

A test harness for cucumber and rspec allows for separating responsibility between setting up the context and interacting with the browser and cleaning up the step definition files

10) Explain when to use Rspec and when to use Cucumber?

    Rspec is used for Unit Testing
    Cucumber is used behaviour driven development. Cucumber can be used for System and Integration Tests

11) What is the language used for expressing scenario in feature file ?

Gherkin language is used to express scenario in feature files and ruby files containing unobtrusive automation for the steps in scenarios

12) Explain what is regular expressions?

A regular expression is a pattern describing a certain amount of text.  The most basic regular expression consists of a single literal character

13) Explain what is BDD (Behaviour Driven Development) ?

BDD or Behaviour driven development is a process of developing software based on TDD (Test Driven Development) which focusses on behavioural specification of software units.

14) What softare do you need to run a Cucumber Web Test ?

    Ruby and its Development Kit
    Cucumber
    IDE like ActiveState
    Watir ( To simulate browser)
    Ansicon and rspec (if required)

15) What does a features/ support file contains?

Features/ support file contains supporting ruby code. Files in support load before those in step_definitions, which can be useful for environment configuration.