Friday 27 December 2013

Using PhantomJSDriver(),We can speedup selenium webdriver scripts execution

Example script:

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.testng.annotations.Test;


public class TestPhantomJS {


@Test

public void GoogleSearch(){

WebDriver driver = new PhantomJSDriver();

//  WebDriver driver = new FirefoxDriver();

driver.get("http://google.com");

driver.findElement(By.name("q")).sendKeys("phantomjs");

driver.findElement(By.name("q")).submit();

List<WebElement> sites = driver.findElements(By.xpath("//cite"));

System.out.println(driver.getTitle());

int index=1;

for(WebElement site: sites){

String siteName=site.getText();

if(!siteName.equalsIgnoreCase(""))

System.out.println(index+++":--"+site.getText());

}

driver.close();

}


}

//Copied this from web

Most common functions using in Selenium WebDriver

  1. IsElementPresent/Text Present  function in Selenium WebDriver
    1. Finding elements by using function that take argument of By classprivate boolean isElementPresent(WebDriver driver, By by)
      try{
      driver.findElement(by);
      return true;
      }
      catch(Exception e)
      {
      return false;
      }
      }
    2. Using the size to decide whether element is there or not
      if(driver.findElements(Locator).size()>0
      {
      return true
      }else
      {
      return false
      }
      }
    3. Finding the text using the PageSourcedriver.PageSource.Contains("TEXT that you want to see on the page");
  2. Finding WebElement  by using various locators in WebDriver
    1. Using ID  WebElement welement = driver.findElement(By.id("Id from webpage"));
    2. Using Name  WebElement welement = driver.findElement(By.name("Name of WebElement"));
    3. Using Tag Name  WebElement welement = driver.findElement(By.tagName("tag name"));
    4. Using Xpath  WebElement welement = driver.findElement(By.xpath("xpath of  webElement"));
    5. Using CSS  WebElement welement = driver.findElement(By.CSS("CSS locator path"));
    6. Using LinkText  WebElement welement = driver.findElement(By.LinkText("LinkText"));
  3. Fetching pop-up message in Selenium-WebDriver
    this is the function that would help you in fetching the message

    public static String getPopupMessage(final WebDriver driver) {
    String message = null;
    try {
    Alert alert = driver.switchTo().alert();
    message = alert.getText();
    alert.accept();
    } catch (Exception e) {
    message = null;
    }
    System.out.println("message"+message);
    return message;
    }
  4. Canceling pop-up in Selenium-WebDriver
    public static String cancelPopupMessageBox(final WebDriver driver) {
    String message = null;
    try {
    Alert alert = driver.switchTo().alert();
    message = alert.getText();
    alert.dismiss();
    } catch (Exception e) {
    message = null;
    }
    return message;
    }
  5. Inserting string in Text Field in Selenium-WebDriverpublic static void insertText(WebDriver driver, By locator, String value) {
    WebElement field = driver.findElement(locator);
    field.clear();
    field.sendKeys(value);
    }
  6. Reading ToolTip text in in Selenium-WebDriver
    public static String tooltipText(WebDriver driver, By locator){
    String tooltip = driver.findElement(locator).getAttribute("title");
    return tooltip;
    }
  7. Selecting Radio Button in Selenium-WebDriver
    public static void selectRadioButton(WebDriver driver, By locator, String value){ List select = driver.findElements(locator);
    for (WebElement element : select)
    {
    if (element.getAttribute("value").equalsIgnoreCase(value)){
    element.click();
    }
    }
  8.  Selecting CheckBox in Selenium-WebDriver

    public static void selectCheckboxes(WebDriver driver, By locator,String value)
    {
    List abc = driver.findElements(locator);
    List list = new ArrayListArrays.asList(value.split(",")));
    for (String check : list){
    for (WebElement chk : abc){
    if(chk.getAttribute("value").equalsIgnoreCase(check)){
    chk.click();
    }}}}
  9. Selecting Dropdown in Selenium-WebDriverpublic static void selectDropdown(WebDriver driver, By locator, String value){
    new Select (driver.findElement(locator)).selectByVisibleText(value); }
  10. Selecting searched dropdown in Selenium-WebDriverpublic static void selectSearchDropdown(WebDriver driver, By locator, String value){
    driver.findElement(locator).click();
    driver.findElement(locator).sendKeys(value);
    driver.findElement(locator).sendKeys(Keys.TAB);
    }
  11. Uploading file using  Selenium-WebDriverpublic static void uploadFile(WebDriver driver, By locator, String path){
    driver.findElement(locator).sendKeys(path);
    }
  12. Downloading file in Selenium-WebDriverHere we will click on a link and will download the file with a predefined name at some specified location.
    public static void downloadFile(String href, String fileName) throws Exception{
    URL url = null;
    URLConnection con = null;
    int i;
    url = new URL(href);
    con = url.openConnection();
    // Here we are specifying the location where we really want to save the file.
    File file = new File(".//OutputData//" + fileName);
    BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
    BufferedOutputStream bos = new BufferedOutputStream(
    new FileOutputStream(file));
    while ((i = bis.read()) != -1) {
    bos.write(i);
    }
    bos.flush();
    bis.close();
    }
  13. Handling multiple Pop ups 
    read  Handling Multiple Windows in WebDriver
  14. Wait() in Selenium-WebDriver
    1. Implicit Wait :
      driver.manage.timeouts().implicitlyWait(10,TimeUnit.SECONDS);
    2. Explicit Wait:WebDriverWait wait = new WebDriverWait(driver,10);
      wait.until(ExpectedConditons.elementToBeClickable(By.id/xpath/name("locator"));
    3.  Using Sleep method of java
      Thread.sleep(time in milisecond)
  15. Navigation method of WebDriver Interface
    1. to() method (its a alternative of get() method)
      driver.navigate().to(Url);
      This will open the URL that you have inserted as argument
    2. back() – use to navigate one step back from current position in recent history syntax == driver.navigate().back();
    3. forward() – use to navigate one step forward in browser historydriver.navigate().forward();
    4. refresh() – This will refresh you current open urldriver.navigate().refresh();
  16. Deleting all Cookies before doing any kind of action  driver.manage().deleteAllCookies();
    This will delete all cookies
  17. Pressing any Keyboard key using Action builder class of WebDriverWebDriver has rewarded us with one class Action to handle all keyboard and Mouse action. While creating a action builder its constructor takes WebDriver as argument. Here I am taking example of pressing Control key
    Actions builder = new Actions(driver);
    builder.keyDown(Keys.CONTROL).click(someElement).click(someOtherElement).keyUp(Keys.CONTROL).build().perform();
    When we press multiple keys or action together then we need to bind all in a single command by using build() method and perform() method intend us to perform the action.
    In the same way you can handle other key actions.
  18. Drag and Drop action in Webdriver
    In this we need to specify both WebElement  like Source and target and for draganddrop Action class has a method with two argument so let see how it normally look like
    WebElement element = driver.findElement(By.name("source"));
    WebElement target = driver.findElement(By.name("target"));
    (new Actions(driver)).dragAndDrop(element, target).perform();
  19. Reference site
    http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/
  20. http://abodeqa.wordpress.com/2013/09/18/webdrivers-most-popular-commands/

Sunday 22 December 2013

Simple Blog creation using Rails(MVC)

Setting up our Rails app

rails new quick_blog -T
Entering this command into your command prompt will cause Rails to generate a new application and begin to install dependencies for your application. This process may take a few minutes, so you should let it continue. Once it has finished type:
cd quick_blog
To change into the folder where your application is stored. If you look at the contents of this folder you’ll see:
The default Rails application structure
This is the standard structure of a new Rails application. Once you learn this structure it makes working with Rails easier since everything is in a standard place. Next we’ll run this fresh application to check that our Rails install is working properly. Type:
rails server
Open your web-browser and head to: http://localhost:3000 you should see something that looks like:
Rails default homepage
Now that you’ve created the Rails application you should open this folder using Sublime. Open up Sublime, then open the quick_blog folder that was just generated.

Creating basic functionality

Now we’re ready to get started building an actual blog. In your command prompt press Ctrl-c to stop the Rails server, or open a new command prompt and navigate to your Rails application folder. Then you can use a Rails generator to build some code for you:
rails g scaffold Post title body:text
You’ll be presented with something that looks like:
Scaffolding posts
An important file that was generated was the migration file: db/migrate/20130422001725_create_posts.rb Note that you will have a different set of numbers in yours.
class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.string :title
      t.text :body

      t.timestamps
    end
  end
end
This file is some Ruby code that is a database agnostic way to manage your schema. You can see that this code is to create a table called Posts and to create two columns in this table, a title column and a body column. Finally we need to instruct Rails to apply this to our database. Type:
rake db:migrate
Once this command has run you can start up your Rails server again with rails server and then navigate tohttp://localhost:3000/posts to see the changes you’ve made to your application.
Empty posts list
From here you can play around with your application. Go ahead and create a new blog post.

Ruby on Rails configuration on MAC

Install Rails installer using this link:http://railsinstaller.org/en

You can follow these below steps for installation of Ruby ,Rails through terminal.

1) Download Xcode from Apple Application Store :
use this link : xcode
2) Install xcode :
    a)Use finder=>applications to locate "Xcode installation icon and double-click on it to begin the     installation
     b.) For xcode 4.3. After installing xcode, launch it, navigate to Xcode->Preferences, Downloads tab. Install Command Line Tools. This will download and install C, compiler, loader and other command line utilities needed to compile & build the Ruby packages.

If the above option is not showing in the window go to terminal and type xcode-select --install(this will install command line tools)

3) use a terminal to install git:
gem install git
and put this line in your .bash_profile (create one if none exists) :
export PATH=$PATH:/usr/local/git/bin/

4) use a terminal to install rvm:
bash < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer )
and run this command to update your .bash_profile :
echo '[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # Load RVM function' >> ~/.bash_profile

5) use a terminal to install ruby 2.0 and rails:
rvm autolibs enable 
rvm install 2.0
rvm --default 2.0
gem update
gem install rails


6)Install Sublime IDE