02 November 2012

Capybara and jQuery

One of the nice things about Cucumber, is the variety of different elements you can add to the stack.  Typically you have in an automation framework:
1. base language
2. framework itself
3. web driving technology (for front end tests)

In GEB it's like this:
1. Groovy
2. GEB (which adds Spock for the BDD ability)

In Cucumber you have a lot of choice  here:
1. Ruby/Java/Groovy/etc
2. Cucumber (which has Gherkin for the BDD ability)
3. Watir/Capybara/Webrat
4. you can throw other stuff on the stack, like Rspec, etc.

I was asked recently, "why do you use Watir for your Cucumber/Ruby tests?"  I basically answered "well because it was there."  It was the first web driving/controlling element to the stack I used.  There are other choices, there is Capybara for example.

While I'm new to Capybara, there are some interesting things I've found with it.  One of the nice things is the ability to execute scripts.  I don't know how to do this with Watir (and hence I'm assuming it's not possible) to execute Javascript or JQuery. 

But in Capybara you can do something like this (examples taken from jnicklas):
page.execute_script("$('body').empty()")
 
Sure enough, Ruby can be used to do calculations (so I'll omit that example.)
What's great about this, is that I can run jQuery.... and what's so great about jQuery?  Well if you use Firebug in firefox, it has a console that lets you run/execute jQuery in the page.  Sometimes elements in dynamic pages, can be a trick to find and manipulate.  I find this true with Microsoft pages for example (like windows.com) - jQuery makes this easier... here's why:

  1. If you work on a team,  you have a front end dev who's usually a wizard of jQuery... so such a person can easily give you query or improve your own to find or manipulate elements on the page
  2. I have found situations where Watir has such a hard time finding an element, and jQuery finds the element fine
  3. jQuery is tried and true and  has a strong community backing it
  4. Firefox lets you run jQuery from the firebug console... this way you can verify what elements you can manipulate and how you can access them.
You can find more about jQuery at: http://docs.jquery.com/

Capybara lets a person run jQuery by simply doing a: page.execute_script and then passing the jQuery in.

Again, maybe Watir has a method of doing this, I haven't found that to be the case though - so when I get in a bind, I use Capybara's execute_script functionality to run jQuery as needed.

The testing stack I personally use for automation allows for using Capybara, along with Watir's easier (imo) way of managing the browsers:
group :test, :development do
  gem 'cucumber-rails'
  gem 'database_cleaner'
  gem 'rspec'
  gem 'spork'
  gem 'capybara'
  gem 'watir-webdriver'
  gem "gherkin", "~> 2.11.2"
end

No comments:

Post a Comment