Tuesday, October 22, 2013

Cross Browser/Cross Platform Automated Testing with Ruby


As developers, we’ve typically developed cross browser applications but now, with the advent of mobile devices, there’s a new plethora of devices to develop against.  How do we test against these? 
Cucumber + Watir-WebDriver + Appium = Cross Browser, Cross Platform Testing
We’ll walk through the highlights of setting up each browser and platform and also to capture screenshots.
The full code is available from my Github:  https://github.com/matthewbussa/watir-webdriver-demo
In order to start with, you’ll need the following software:
  • Ruby 1.9.3
    • Cucumber gem
    • Watir-WebDriver gem
  • Appium – please note that support for Appium in Windows is in “beta”
  • XCode
    • Install the Command Line tools (XCode –> Preferences –> Downloads –> Command Line Tools
    • Install the 6.1 Simulator in the same place
  • GenyMotion – free account is required.  Ensure you have Oracle VirtualBox installed before installing Genymotion

Cucumber Scenario to test:

Scenario: "Capture screenshot for one device and platform"
    Given I am on the home page
    Then a screenshot is captured

Setting up the Browser

With Watir-WebDriver it’s easy to setup in instance of a Watir Browser and initiate it for different browsers or platforms.  Below are some examples on how to utilize this feature:

FireFox

setup_firefox()
    browser = Watir::Browser.new :firefox
    browser.driver.manage.window.maximize
    browser
end

Chrome

For Chrome, you’ll need to download ChromeDriver v2.2  and place it in your class path.  Be sure to start the chromedriver before running your tests.  At the time of this writing, ChromeDriver v2.3 was not compatible.  The following is the Ruby code to setup an automated Chrome browser: 
setup_chrome()
    browser = Watir::Browser.new :chrome
    browser
end

For iPhone, iPad, and Android, ensure that Appium is up and running on the default port of 4723.  Appium will automatically load the iPhone and iPad devices however, it doesn’t automatically shut them down.  This can easily be done using the “kill ‘iPhone Simulator’” or kill ‘iPad Simulator’ commands from the terminal.

iPhone

setup_iphone()
    capabilities = 
    {
        'device' => "iPhone Simulator",
        'browserName' => 'iOS',
        'platform' => 'Mac',
        'version' => '6.1',
        'app' => 'safari'
    }

    server_url = "http://localhost:4723/wd/hub/"
    driver = Selenium::WebDriver.for(:remote,
                 :desired_capabilities => capabilities,
                 :url => server_url)
    browser = Watir::Browser.new driver
    browser

end

iPad

The iPad version is the same as the iPhone setup with the exception that the ‘device” capability is different. 
setup_ipad()
    capabilities = 
    {
        'device' => "iPad Simulator",
        'browserName' => 'iOS',
        'platform' => 'Mac',
        'version' => '6.1',
        'app' => 'safari'
    }

    server_url = "http://localhost:4723/wd/hub/"
    driver = Selenium::WebDriver.for(:remote, 
                 :desired_capabilities => capabilities, 
                 :url => server_url)
    browser = Watir::Browser.new driver
    browser

end

Android

In order for Android to work, ensure you have both Appium running and that you have an Android Emulator up using Genymotion. Also ensure that the Android Emulator you are using has the Chrome browser installed. This can be installed through the emulator's play store. A Gmail account will be needed to log into the Play Store.
setup_android()
  capabilities =
  {
  'app' => 'chrome',
  'device' => 'Android'
  }

  server_url = "http://localhost:4723/wd/hub/"
  driver = Selenium::WebDriver.for(:remote, 
               :desired_capabilities => capabilities, 
               :url => server_url)
  browser = Watir::Browser.new driver
  browser.driver.manage.timeouts.implicit_wait = 30
  browser

end

Capturing the Screenshot

The logic to capture a screenshot is fairly straightforward for non-Android devices.  However, Android devices are a bit tricky.  We need to save the screenshot to the sdcard on the emulator, then move the file to our location and finally, do some cleanup and delete the image on the sdcard.

def capture_screenshot()
  time = Time.now.to_i.to_s
  filename = time + '.png'
  if (platform == 'android')
    %x(adb shell /system/bin/screencap -p /sdcard/screenshot.png)
    %x(adb pull /sdcard/screenshot.png ./screenshots/screenshot.png)
    FileUtils.mv('./screenshots/screenshot.png', filename)
    %x(adb shell rm /sdcard/screenshot.png)
  else
    browser.driver.save_screenshot filename
  end

  filename
end

If you’re already using Cucumber and Watir-WebDriver for your automated web testing, Appium makes it easy extend your coverage utilizing the existing tool set and begin testing on mobile devices and if you’re not, here’s a framework to get you started!

Happy Testing!


Update 11/11/2013:  With the XCode 5.0, Apple removed the ability to launch built in applications.  This means that if you use XCode 5.0 or above, Appium will not launch Mobile safari, which is what the tests are setup to do.

No fear, the solution is to ensure you have XCode 4.6.3 and iOS Simulator 6.1.  You can download the older version here:  https://developer.apple.com/downloads/index.action#

There's some documentation on how to switch between versions of XCode from Appium here:  https://github.com/appium/appium/blob/master/docs/running-on-osx.md

Saturday, August 17, 2013

My First Advocare 24 Day Challenge Experience

My wife and I started the 24 day challenge on July 8. Our motivation for going down this journey was primarily for our boy/girl twins. To sweeten the pot a bit, we both also signed up for healthywage.com for longer term motivation. We are both obese and wanted to form healthier habits in order to gain more energy but most of all to maintain these healthier habits so when the twins get to the point of eating solids, we can teach them good habits in hopes they won't have the same struggles as we have had. We didn't want a diet, we wanted a lifestyle! After hearing multiple friends having great success with Advocare, we decided to try it.


Before Advocare 


I was a frequent fast food/restaurant shopper. I'd often go to McDonalds for breakfast, go out for lunch, then have dinner at home and snack in between. I did more than my share of mindless eating and snacking. I would go out to lunch most days at work mostly because everyone else was doing it and not really eating healthy. Never really paid attention to what was going into my mouth. We don't have control over a lot of things in our lives but we do have control over what goes into our mouths!

A day before we started Advocare, we decided we would have somewhat of a "last meal". Mine was Skyline Chili. Yum!

Then we started...

Days 1-10 


First day of Advocare, we started the morning with the Spark (Grape and Fruit Punch are my favorites) and followed up with the Fiber Drink and necessary pills. The Fiber Drink was disgusting, tasted like pulpy cardboard! You need to drink this fast else it turns to a thick slush. The taste is somewhat improved if you mix it with the Mandarin Orange Spark, tastes more like orangey, pulpy cardboard.

The first few days I had very bad headaches, primarily in the evenings. For me, I think it was somewhat of sugar withdrawl but also I would skip eating snacks primarily because I was working and couldn't work it in. I ended up taking headache medicine the first few days to help calm them down. I was forced to work the snacks in at work. Over time, eating snacks did get somewhat better. I would at least eat one snack per day (you should eat 2) but not optimal.

We made meal changes like wrapping lettuce in turkey burgers instead of having hamburgers with cheese and a bun. It is a change but I didn't miss the bread or cheese nearly as much as I thought I would!

After the first couple days, the challenge became more routine. We really watched we ate and became more mindful of the food decisions we were making. I quit going out to eat cold turkey. It's amazing how much money you spend going out to eat and how much more money you have when you stop! I began taking salads and left overs from the previous nights supper for lunch.

The biggest health habit we took from the first 10 days was to fix stone cut oatmeal and eggs with salsa every morning. We would fix a crockpot recipe of oatmeal over the weekend and just heat it up every morning. This is a habit we've continued after the challenge. I put salsa on a ton of stuff nowadays!

After the first week, I lost 14 lbs!

The following week came around, headaches were gone and I learned that I was beginning to form healthier habits! We continue to follow the Advocare challenge and the second week was drastically reduced but still lost 2.6 lbs!

Days 11-24


We largely stayed on the same routine as days 1-10 with the exception of we swapped out eggs and oatmeal for breakfast for the meal replacement breakfast shakes. I had the Chocolate flavored. I was impressed by the flavor. I've had protein shakes before and am not a big fan of the taste, too chalky. This was like a chocolate milkshake. I'd just mix it with water but if you mix it with ice and put it in the blender, it's even better because you don't have clumps in it! These meal replacement shakes were definitely more convenient! 

The biggest challenge during this time was taking the larger MNS pills. They are about the size of the One-A-Day pills. I've always had trouble taking pills. This period of the challenge, you do take a lot of pills! I had trouble swallowing the larger ones. I ended up mixing the pills with natural, no sugar added applesauce. This coated the pills and eventually made it much easier to swallow but it was an adjustment for me!

In regards to diet, we continued eating lean meat, salads and developing healthier habits. One of my favorite meals now is taco salad! Don't think big taco shell, this taco salad has ground turkey with taco seasoning with lettuce, green pepper, and onion and top it off the salsa and maybe even some sunflower kernels! Yummy!

After day 21 I lost another 6 lbs and after 24 days, I lost a total of 24 lbs! This was strictly diet changes. I didn't change anything in regards to physical activity.

For inquiring minds, my wife ended up losing a total of 21.4 lbs!

After Advocare 


I'm writing this a few weeks after finishing the challenge. While not at the Advocare rate, I am continuing to lose weight. For the most part we have continued our healthy eating habits. We continue to fix eggs and salsa in the morning and have healthy dinners. I've only gone out to lunch once at work and continue to take left overs for lunch. Some of my co-workers have even started packing!

For a week or so after the challenge I felt hungry A LOT and even still do to some degree! The Advocare appetite suppressants really work! My wife and I have continued to encourage each other. I could not have gone down this journey without her!

We hope and pray that we continue going down this healthier way of living both for our health as well as our growing babies health. I'm grateful for all my friends and family in being encouraging during this time and even sometimes adjusting meals to be more "Advocare friendly".

We have decided we are going do another 24 day challenge towards the end of the year. You're supposed to wait 3 months before doing it again. I'm excited to see what the results from those will be! My goal is to incorporate exercise this time around!

I would highly recommend anyone try Advocare both to lose weight but also to begin forming healthier habits. We went into this not thinking this is a diet but a new lifestyle. Advocare is a springboard to changing your life!

Monday, September 17, 2012

Importance of a Complete Vertical Slice

What's a vertical slice?  Think of a delicious layered cake.  Say we have 3 layers and you slice a piece.  A thin slice of each layer produces one solid piece.  Think of the cake layers as architectural pieces: database layer, services layer, the user interface layer, etc..  Each of these layers are as important as the last to get to the final goal: a solid, functional piece of software.

In any project, especially a green field project, building in vertical slices is critical to success.  A solid vertical slice proves two things: 
1.) Proven architecture
2.) Produces a complete, functional, shippable piece of working software that works from end to end.

The risk of not having a Vertical Slice

Not having a vertical slice presents an unproven architecture and much unneeded risk.  Not having a vertical slice poses the possibility that the entire database is built with no user interface or service layer, or the opposite, a great looking UI and service layer but the data model is a mess and not scalable.  Either way, much rework is involved for further scalability.  Having a proven architecture by developing in vertical slices allows you the ability to continue working and not end up with a fantastic UI but a non-scalable database model.

Don't forget ETL (Extract Transform Load)

When developing a vertical slice, consider the notion of having to importing existing data.  Does this change the implementation?  Can the data model be simplified or restructured to suite an ETL more effectively?  While I'm not saying to develop an application for the sole purpose of an ETL, the ETL needs to be considered in the vertical slice.

But individuals know one layer...

WRONG!  One characteristic of a good agile team are generalized specialists.  Individuals who may specialize in one layer or area but also able to build up the layers.  Ideally, team members' skills should complement each other's in order to create an effective synergy.  Have team members pair often to help facility the synergy and allow team members to grow from one another.  This type of cross functional team mentality allows vertical slices to be built effectively.  Thus coming to value added software quicker.

Identifying the vertical slice and developing a story via a vertical slice rather than by architectural layers proves the architecture and produces a piece of quality, shippable software faster.

Monday, July 9, 2012

URGENT vs. IMPORTANT

We've all had them, clients who have a mile long feature list and want everything now! While the enthusiasm and excitement may be encouraging, it's time to get real.  Realistically, every feature is not going to get developed now, it's just not possible.  Prioritization needs to happen to determine what the team should work on first.  How do you prioritize?  How do you go from a mile long list of features to a much leaner, prioritized backlog that a team can burn through?  One way is by having the urgent vs. important discussion.

The Urgent vs. Important Chart

uvi

This graph can help visualize and put in perspective what is urgent vs. what is important and take us one step closer to a groomed, prioritize backlog.

Here are a couple examples:
-Broken arm
-Need eventual surgery

How would you rate these, urgent or important?

A broken arm is clearly both high on the urgent and important scale.  This requires immediate attention whereas having the need for eventual surgery is very important, however, it's not as urgent as a broken arm.

Let's equate this to the software world:
-Fatal bug that needs fixed
-Adding Authentication

Where would you rate these on an urgent vs. importance chart?  Clients getting a big visible bug is clearly both urgent and important while a feature to include authentication is very important but not nearly as urgent. 

This visual aid helps put in perspective that everything is not as urgent and important as one may originally think.Take a step back and take a hard look at what is urgent vs. what is important to help prioritize the backlog to ensure the team is working on the most important and the most urgent task at any given time.  A well groomed, prioritized backlog is vital to adding value and getting feedback as quickly as possible.

Monday, March 19, 2012

Connect Rails 3.1 From Mac OS X to SQL Server


I’m currently using Ruby on Rails 3.1 and am developing on a Mac.  A requirement was to use MS SQL Server as the database.  There are a couple hoops to jump through to get RoR to work with SQL Server.  Fortunately, the Tiny TDS gem made this a breeze to setup without having to go through the headache of unixodbc/iodbc/rubyodbc configuration.

Here’s the following steps to accomplish:

1.  Install FreeTDS using brew

brew install freetds

2.  Add the following gems to the Gemfile

  gem 'activerecord-sqlserver-adapter'
  gem 'tiny_tds'

3.  Run bundle install to update the gems

4.  Modify the database.yml file to the following:

development:
    adapter: sqlserver
    mode: dblib
    dataserver:   <IP Address>\<Instance Name>
    database: database_name
    username: sql_user
    password: sql_password

Things of note:


1.  Additional ways to configure the connection string can be found here

2.  If you’re using a named instance of SQL, it’s not going to use the default 1433 port.  Through SQL Management Studio, you can run the following command to find out what port your instance is running on:

use master
go
xp_readerrorlog

Troubleshooting


If this doesn’t initially work, there are a couple potential points of failure.  Here are some of the debugging techniques I used to verify I could connect to SQL Server without rails:

1.  Verify that you can make a connection to SQL Server.  From terminal prompt, do the following:

telnet <IP Address> <port>

If you connect, you'll receive the following:

Trying 192.168.31.128...
Connected to 192.168.31.128.
Escape character is '^]'.


2.  Once you’ve verified that you can connect using telnet, second step is to verify that you can connect via FreeTDS.  From the terminal prompt, do the following:

tSQL –H <IP Address> –p <Port> –U sa -P password

If connected properly, you should see the following prompt:
locale is "en_US.UTF-8"
locale charset is "UTF-8"
using default charset "UTF-8"
1>

At this point, this is a SQL editor so you could use SQL syntax to extract queries.  For our purposes, we just want to verify that we can connect this way. 

Type exit to exit out of application

3.  I also ran into an issue when connecting using Rails I received the following error “Adaptive Server timeout”.  I resolved this by doing another bundle install and it has worked after that.

Happy Developing!

Saturday, March 3, 2012

SpecFlow 101

SpecFlow is a Behavior Driven Development (BDD) tool for .NET.  SpecFlow has brought the Gherkin language to .NET and to Visual Studio!  This post will set you up quickly with SpecFlow with a simple example.  

Install

Download the latest SpecFlow install

New Visual Studio Templates

image

Once installed, there are three new Visual Studio templates that will be installed including the

  • Event Definition – this template is to be used for more of global hooks such as
  • Feature – template to write out the feature with scenarios in Gherkin language
  • Steps Definition – template to store the steps from the feature file that will execute the code and do assertions

Our Feature Example

For this example, we’ll use the Roman Numeral kata.  While this is a relatively simple kata, the purpose is to help navigate through SpecFlow.  So, let's begin:

1.  Create a new project and create a SpecFlow Feature File:

image

2.  Create a SpecFlow Step Definition File

The Step Definition template has code with sample steps in the class.  Delete everything inside the class but not the class itself.

3.  Generating Steps from Feature file

There are a couple of different ways to generate steps once a scenario is given.

  • Step by Step – with your cursor over a scenario step, press F12.  image

SpecFlow will offer to put the step binding skeleton in your clipboard and then it can be easily pasted into your steps definition file.  Note that if the step already exists, Specflow will navigate you to the step definition automatically, just like F12 does with “GoTo Definition”.

This is useful when you’re creating a new feature and want to take one step at a time versus having numerous pending steps.  I find this useful when you want to take things one at a time.

  • Bulk Create

Using TestDriven.Net right click on the feature designer file (extension of .feature.cs) click “Run Test(s)”.  For each scenario, SpecFlow will create a task that contains a StepsDefinition class.  This class can be copied and pasted into the steps definition file.   It should look like the following:

image

Observations:

  • With each generated step, the result will be Pending
  • One class per scenario.  When generating steps, SpecFlow will generate one steps definition class that is in the feature file if none exists.  There could exist the same step in multiple scenarios, neither of which have been generated yet.  When pasting in the generated steps, you’ll get compile errors telling you of duplicate steps.  Delete the duplicate steps and you’re golden.
  • If two of the same steps exists and you manually change the method name but leave the regex decorator the same, there will be a runtime error noting ambiguous steps.
  • If attempting to navigate to a step from a feature file with multiple regex step definitions matching, SpecFlow will throw a dialog box up stating ambiguous steps and will navigate to the first one.

Developing Code to Make The Test Pass

By default, SpecFlow is setup to use NUnit.  You can configure SpecFlow to use MSTest, if so desired.  Generate the steps with the correct xUnit assertion statements to make the tests pass for each step. 

Running Tests

Running Tests are very similar to generating the steps.  Once the steps are generated and beautiful code is written to get the tests to pass, right click on the feature designer file and click “Run Test(s)”.  If steps within a scenario are still pending, the following message will be displayed:

image

Hopefully this gets you familiar with SpecFlow and some of the advantages of this tool being integrated into Visual Studio.  Happy trails with your SpecFlow journey!

Sunday, November 13, 2011

My First Week on a MacBook Pro

I’ll admit it, I’ve been a Microsoft fan boy for all my life.  I’ve only owned Microsoft products (even a Zune!), never really gone outside my comfort zone and experienced the “other side”.  For the last week, I’ve been working on a MacBook Pro and, must admit, am really enjoying the experience.  From my employer, I had the option between a PC and a Mac laptop.  I chose a Mac for a couple for a couple of reasons:  1.) I wanted to broaden my OS horizons and learn something new and 2.) The option of potentially doing Mac iOS development is now an option.  I can create a Windows VM (which I have) on a Mac but the other way (creating a Mac VM on a Windows machine) doesn’t work out so well.  So, with that, here’s been my first experiences with the Mac and why I’m enjoying it.

Setup

Setup was a breeze.  Within a few minutes I was up and running with OS X Lion.  Once loaded, I was excited to get started so, off to the App Store I went.  The first thing you’ll want to do is to sign up for a free App Store ID.  This will enable you to download things from the App Store, both free and paid.  There are many great Apps in the App Store to get you started!  I’ve also notice that installing applications are easy, it’s literally a drag and drop into the Applications folder.  It takes away all the “Next, Next, Next” that a Windows setup has a user to do.

Software

  • VMWare Fusion (paid) - this is a great VM product for Mac.  Since I still do the majority of my development in .NET, I needed a Windows machine to develop in.  I had an option of Boot Camp (basically dual booting) into Windows or creating a VM.  I chose a VM for a variety reasons.  Creating a Windows 7 64 bit VM with Fusion was super easy.  It first asked to give it a user name and password and it was off.  I didn’t need to enter any other piece of configuration data.  The VM has been running smoothly all week.  Full disclosure:  I did upgrade the RAM to 8GB and have dedicated 5.5GB or RAM to my VM.
  • Alfred (free in the app store) - this is a quick productive tool designed to keep your hands on the keyboard.  With Alt + Space bar, we can launch Alfred and have it search what we are looking for whether it be locking your system to searching for something locally or on the internet, Alfred can help.
  • Twitter (free from app store) - the Twitter app for the Mac is fairly impressive.  It has a time line bar and everything that Twitter has to offer in a good layout and it’s easy to use.

 

Developer Tools

  • XCode - this is the IDE of choice for Apple development.  While I did experience some serious lag in downloading this application, once up and running it does install easy.
  • HomeBrew - package management tool

Blogging Tools

For me, I find it best when I write a blog to initially write in a “distraction free” writing zone.  That is, an application that is full screen, I can’t see any notifications nor icons that tempt me to get distracted.  Often I’m ADD and just want to click on the next shiny thing so a good distraction free writing tool helps me immensely in writing!  I was looking for a good one for a Mac and found two free ones and haven’t made up my mind which I enjoy more:
  • FocusWriter - I am admittedly writing this blog post in this tool.  I like the fact that you can create and Import/Export Themes.  I am a big fan of a high contrast theme so the first thing I done was created a “Retro” theme with a black background, black foreground, and green text.  Back to the good ole green screen it is!  FocusWriter has a Timer that will go off after set number of minutes.  This is useful if you are using a Pomodoro technique and it also helps keep me focused for a set number of minutes.
  • OmniWriter - this is another great distraction free writing tool.  This gathers more senses than just your sight.  Omniwriter envelopes you in a zen like environment complete with a soothing background and writing space and playing zen like music.  It definitely puts you in a much more relaxed state to allow your ideas to flow freely.

Key Observations

I’ve consistently heard that Apple is great at improving things and that “it just works”.  I have found this to be true in the different accents they put on their product.  Some things I noticed are:

Power Brick

First off, it’s a relatively small power brick that you can easily pack away.  There are small, yet useful improvements such as cable management that allows you to clip the cord to itself not to mention the magnetic plug that plugs right into the laptop.  The little adapter where you can plug the power brick directly into the wall or attach a longer power cord to the power brick for more cord length.  Typically I just use the power brick and not the longer power cord as this is easier to pack away in a bag.

Spaces

Having this concept of multiple Spaces I found very useful.  With a 3 finger swipe, I can just swipe between spaces.  This is useful to help organize the applications I’m in.  I typically use this by having my Windows VM up in a space and having other applications that are native to Mac in another space.  This allows me to switch and organize my spaces easily without minimizing/maximizing a bunch of windows.

TrackPad

While I’m mostly a keyboard guy, I was amazed at all the Apple TrackPad can do.  This is much more sophisticated than the TouchPads I’ve used on a Windows machine.  With the TrackPad you can do a three finger swipe to move between workspaces or a two finger click to bring up a context menu or just swipe from side to side in your browser to go between web pages or just do a two finger swipe or down instead of scrolling.  Apple has really made use of the TrackPad and has brought it up to an entirely different level. 

Backlit Keyboard

To be honest, I never thought I’d use a backlit keyboard.  I thought, what’s the use.  I have found a use!  In our Team Space, we enjoy the room dimly light.  It’s easier on the eyes than all the bright halogens.  Since it’s dimly lit, the backlit keyboard provides just enough soft light to make it an enjoyable experience.
Display The display is fantastic!  I got the 15” glossy screen and am enjoying the experience.  It has a nice, sharp, high resolution screen that is much crisper than the ones I have seen on Windows hardware.


Wrap Up

There are many other aspects I’m enjoying but those are my top 5, not in any particular order.  My first week with a MacBook Pro and I’m really enjoying “the other side”.  The broadening of my horizon has proved useful and would encourage PC users to try out the Mac.  I am enjoying the small footprint, both in size and weight that the MacBook Pro has to offer.  There are some “oddities” with keyboard shortcuts such as Command + C to Copy instead of the good ole Windows Ctrl + C to Copy but am learning everyday!  I’m anxious to continue learning new things about the Mac whether it be hardware or software in the coming days.


What other tips/tricks and/or apps do you have that you find useful (free or otherwise?)