Capybara. Can it be that simple?

So, a lot of the testing groups and employers keep telling me "you need to learn Capybara and Rspec to go with your Cucumber!" After fiddling with Capybara, I can tell you why. It makes a lot of test automation about ten times easier and the software is very intelligent.

Before I used Selenium-Webdriver to navigate to different pages, click on buttons, and identified things with HMTL and CSS tags. However, what if I could simply identify something by the text a link is displaying? What if I could just write visit(page) into ruby and it visits the page for me? Things would be much simpler and there would be far less chance of error. Also, I could write my scripts much faster! In this post, I want to concentrate on rewriting the same methods in my TrekToday automated test in Capybara.

In our Given Statement, we told Selenium Webdriver to navigate to a page using the "navigate.to" method. How do we do that in Capybara? Simple: visit(page), where page is the place you want to go to. Now, does that mean Capybara replaces SWD? Not exactly. It's actually using SWD methods to build something a little more intelligent. How do I know? Its in the gem's documentation:

Here you can see that Capybara's visit method is defined using SWD methods. Which is really cool, but also makes this kinda like mathematics. Calculus is good for a lot of things, but you have to understand algebra before you truly understand what's going on. In order to find the code I just found with any gem, go to the Rubydoc page for that gem, find the method, and hit "view source." This really opened up my world! Back to the task at hand:

So now we can visit the page and we have to resize it. Remember Capybara is still using SWD. This is a little more extraneous with Capybara, but you simply assign "Capybara.current_session.driver.browser.manage.window" to the variable window then use the .resize_to(x,y) method on the window variable.

Where this become really easy is the when and then statements. Before we told the driver to find a CSS ID which locates a button and then asked the computer to click it for us. This then took us to the CSI Files site. However with Capybara all we have to do is tell the computer to click the button via the actual text on the button. One thing to remember in this case is to still inspect the element and check out the actual text. Sometimes some fonts are all uppercase no matter what case is input. So the link text for us is "CSI Files" and we can use the "click_link('CSI Files')" method to click the button. Now that we're on the CSI Files site, I want to use the CSI Files logo to see if we have correctly navigated to the site. All I have to do with Capybara is say page.has_content?('CSI FILES'). This really makes our code simpler to read. Here's the final code, so it's a little easier to understand what I did.




No comments:

Post a Comment