November 7, 2021

The Cheezy Internet: Writing Ruby + Watir tests for The-Internet

This is third in a series of blog posts. Care to go back to the beginning?

Last blog entry, based on Jeff "Cheezy" Morgan's LeanPub book, "Cucumbers and Cheese: A Tester's Workshop", we set up our local machine, wrote and executed our first Watir program. 

Based on his book, we are going to attempt to sketch out and write our first test against Dave Haeffner's sample login page on The-Internet at https://the-internet.herokuapp.com/login.

The-Internet / Login Page


Drafting a Test 

A sample test for The-Internet / Login could be:
  • Go to https://the-internet.herokuapp.com/login
  • Enter tomsmith into the username textbox.
  • Enter SuperSecretPassword! into the password textbox. 
  • Press the Login button. 
  • If the Secure Area page does not show "'Welcome to the Secure Area", fail the test.


Finding Locators for Web Elements

How can we interact with the web elements on the site, such as the username and password textboxes, and the Login button? 
  • Open a Chrome browser. 
  • Click on a web element, then right click, selecting "Inspect". 
  • Try to find a tag in the code, such as "id". 
  • If you do that for username you will see: input type="text" name="username" id="username"

Writing a Watir Test


According to Jeff Morgan's Cucumbers and Cheese, we can write an initial Watir script like so:

second-script.rb
require 'watir'
browser = Watir::Browser.new :chrome

browser.goto 'https://the-internet.herokuapp.com/login'

browser.text_field(id: 'username').set('tomsmith')
browser.text_field(id: 'password').set('SuperSecretPassword!')
browser.button(value: 'Login').click

if not browser.text.include? 'Welcome to the Secure Area'
    fail
end


To execute the script, in PowerShell, go into the directory where you saved the script and:
  • ruby second-script.rb

Adding Error Handling


Running the script, a browser will open up, any you will be logged in, but it will PASS in silence.

How do you know it worked? What happens if you change that to check if it says "Welcome to the ThunderDome"?

if not browser.text.include? 'Welcome to Thunderdome'
    fail
end


If we run the code, it now throws the error:

Traceback (most recent call last):
first_script.rb:11:in `<main>': unhandled exception


Hrm. That is inelegant. 

Jeff Morgan suggests we can rewrite this error using Ruby, adding in error handling:

fail 'Text did not match expected value' unless browser.text.include? 'Welcome to the Secure Area'


Refactoring Code Into Methods

"In Ruby, as in many other Object Oriented programming languages, we have named reusable
modules of code called methods55. We have already discussed calling methods but it is also possible
to create your own. Indeed, as we’ll see later, a large part of keeping any Object Oriented automated
testing code (or any code) D.R.Y. involves creating our own classes and methods, as if we were
creating our own little testing language. Method definitions in Ruby have the following form, where
'def' is short for 'define' - Jeff Morgan, "Cucumbers and Cheese".

Let's say we want to declare the browser in a method, we can make "browser" an instance variable.

"Instance variables are available anywhere in the class to which they belong. It made
sense for us in our example to make the browser variable accessible to every method in
our class, because any method in this class would likely need it. And it is messy and noisy
to pass it around to any method that needs it, especially if several methods in a class do
need it" - Jeff Morgan, Cucumbers and Cheese: A Tester's Journey

def goto_login_page
  @browser = Watir::Browser.new :chrome
  @browser.goto 'https://the-internet.herokuapp.com/login'
end

This way, the main body could simply say "goto_login_page", making it much more readable. 

Rewriting what we already have into methods, searching for text that is not actually on the page, it would look like:

third_script.rb
require 'watir'

def goto_login_page
  @browser = Watir::Browser.new :chrome
  @browser.goto 'https://the-internet.herokuapp.com/login'
end

def login_as(username, password)
  @browser.text_field(id: 'username').set(username)
  @browser.text_field(id: 'password').set(password)
  @browser.button(value: 'Login').click
end

def verify_page_contains(text)
  fail "Expected text not found: #{text}" unless @browser.text.include? text
end

def close_the_browser
  @browser.close
end

goto_login_page
login_as('tomsmith', 'SuperSecretPassword!')
verify_page_contains('Welcome to the Thunderdome')
close_the_browser



"Now our testing script is short, sweet, and all about WHAT we are testing. Not only have
we hidden the details of HOW we do this work, we have made that reusable code accessible to any other test module we need [...]" - Jeff Morgan 
Note that now:
  • The script is more readable.
  • Login information is now passed into the login_as method.
  • The verify_page_contains method can search for any text we pass into it. 
  • If we cannot find the text on the Secure area, the failure message will now contain whatever text we were trying to find. 
Running the script, it would output:

third_script.rb:15:in `verify_page_contains': Expected text not found: Welcome to the Thunderdome (RuntimeError)

If you would like even a more detailed example, get a copy of "Cucumbers and Cheese: A Testers Workshop", where Jeff Morgan tests against http://puppies.herokuapp.com/ 

For the next blog entry, we will be scaffolding a project composing these basic building blocks we have created into tests using Cucumber / Gherkin. 



Happy Testing!

-T.J. Maher
Sr. QA Engineer, Software Engineer in Test
Meetup Organizer, Ministry of Testing - Boston

Twitter | YouTubeLinkedIn | Articles

51 comments:

James Anderson said...

Ruby is was my favorite programming language, I love to make code in ruby I also create do my homework program in Ruby. Thank you so much for this lovely information. I really need such type of information.

Sociology Dissertation Help said...

My preferred programming language is Ruby, and I enjoy developing code in it. My homework application is likewise written in Ruby. Thank you very much for sharing this fantastic information with us. This is exactly the kind of information I'm looking for.

thisisemliyblunt said...

I think people underestimate just how far I'm willing to scroll on ASOS It's ordered. asos discount code It's all there in tags and type.

thisisemliyblunt said...

Award Thornton is one of the world's biggest expert administrations organization of free bookkeeping, self assessment services.

July said...

Thanks for suggesting good list. I appreciate your work this is really helpful for everyone.
Regards,
V8web

Great Websites said...

To prepare for the free best practice test, a recent graduate will need approximately 8 weeks of dedicated HNC Assignment study help. Researching could take 6 months or more for designers who have been out of school for more than 10 years. Begin by evaluating the most important test subjects and then taking several technique tests.

thisisemliyblunt said...

Don't we as a whole need assistance in setting aside cash at each a valuable open door Best Discount code site! This application does all the difficult work for yousummer vacation. I frequently find markdown codes that are acknowledged and I've gotten two or three Amazon vouchers by purchasing through VoucherCode's connections london travel guide. Continuously worth hoping to check whether there is a Emporio Armani, voucher that is pertinent. Astounding Beach Vacations! Sets aside heaps of cash in a tap.

Atiqa malik said...

Thanks for sharing this information Also visit my site please Ear Surgery In Islamabad

Casestudysamples said...

case study solver online is the best place to get your assignments done for cheap. We provide order case study help for all types of assignments, from high school to college level assignments.


Anonymous said...

Thanks for sharing this artical, it's really helpful for me. if you are interested to watch movies online but don't want to pay the amount to anyone I am here to give you a free movies please download mirror APK Netflix for free.

Lilly said...

Our experts have years of experience in providing finance assignments help. They understand what students require and deliver the best solution.

John Hardy said...
This comment has been removed by the author.
Hard Shell Suitcase said...

They are some fantastic information for all you have really good and informative blog for all
Best Hard Shell Suitcase

Data Visualization said...


This is a great topic for discussion! As someone who has been writing Ruby and Watir tests for The-Internet for some time, I can say that it has been an incredibly rewarding experience. Not only have I been able to thoroughly test the applications I work on, but I've also been able to learn a lot about the Ruby language and Watir framework. Writing tests for The-Internet has been a great way to hone my coding skills and develop a better understanding of web automation. I'm sure anyone who takes the time to learn how to write such tests will find it a very rewarding experience.

Vivian Raddix said...

I always learn something new from your posts, keep them coming! Looking for an Experienced Visa Consultant Near Me? We Have You Covered.

carrepairdubaiservice1 said...

bmw service dubai offers top-notch maintenance and repair solutions for BMW vehicles, ensuring optimal performance and longevity. With a team of highly skilled technicians and state-of-the-art facilities, they deliver exceptional service to BMW owners in the vibrant city of Dubai. From routine maintenance tasks like oil changes and tire rotations to complex diagnostic procedures and repairs, the BMW Service Dubai team is committed to delivering excellence in every aspect.

havie and moon said...

Step into a world of luxury and indulge in unforgettable beauty experiences at our ladies salon near me . Our exclusive establishment is dedicated to enhancing your natural beauty and providing you with exceptional services that leave you feeling transformed. From expert hair styling and flawless makeup application to rejuvenating spa treatments and personalized skincare, we offer a comprehensive range of services tailored to meet your unique needs. Our team of talented professionals is committed to delivering the highest quality of service in an exquisite environment.

havie and moon said...

Dubai Hills Massage services offer an unparalleled experience of relaxation and rejuvenation in the vibrant city of Dubai. Situated amidst the breathtaking landscape of Dubai Hills Estate, this luxurious spa provides a wide range of treatments and massages tailored to meet the individual needs of each guest. With highly skilled and experienced therapists, state-of-the-art facilities, and a tranquil ambiance, Dubai Hills Massage services ensure a blissful escape from bustling city life.

alpine bear said...

Ontketen uw taktische weste -voordeel met de best beschikbare tactische weste. Ontworpen om je prestaties te verbeteren en essentiële functionaliteit te bieden, bieden deze vesten een ongeëvenaarde veelzijdigheid en bescherming. Met hun innovatieve kenmerken en duurzame constructie zijn ze gebouwd om de meest veeleisende missies te weerstaan. Of je nu bij de politie, het leger of een toegewijde outdoorliefhebber bent, deze tactische vesten geven je de voorsprong die je nodig hebt om uit te blinken in elke tactische situatie. Verbeter je spel en grijp het voordeel met de ultieme tactische uitrusting.

joseph kuruvilla said...

You are providing good knowledge. It is really helpful and factual information for us Inventory management software

alpine bear said...

Sporthandschuhe, zijn essentiële accessoires voor sporters en fitnessliefhebbers. Ontworpen om comfort, bescherming en verbeterde grip te bieden, biedt Sporthandschuhe een scala aan voordelen bij verschillende sporten en activiteiten. Of het nu gaat om gewichtheffen, fietsen of boksen, deze handschoenen helpen de prestaties te verbeteren en het risico op blessures te minimaliseren. Met hun duurzame materialen en ergonomische ontwerpen is Sporthandschuhe een praktische keuze voor iedereen die zijn sportervaring wil optimaliseren.

alpine bear said...

De gids voor taktische rucksaecke voor elke missie is een uitgebreide bron die essentiële informatie biedt voor het selecteren van de perfecte rugzak voor elke tactische onderneming. Of je nu een outdoorliefhebber, een militaire professional of een survivalist bent, deze gids biedt waardevolle inzichten over belangrijke factoren zoals duurzaamheid, opslagcapaciteit, comfort en organisatorische kenmerken. Van robuuste ontwerpen die zijn gebouwd om extreme omstandigheden te weerstaan tot veelzijdige opties met aanpasbare compartimenten, deze gids voorziet je van de kennis die nodig is om een weloverwogen keuze te maken, zodat je rugzak een essentiële metgezel wordt op elke missie.

alpine bear said...

Onthulling van de ultieme gids voor leren arbeitshandschuhe leder.Deze gids biedt een diepgaand inzicht in de wereld van leren arbeitshandschoenen en de verschillende aspecten die van belang zijn bij het kiezen van de juiste handschoenen. Van materiaalkeuze tot pasvorm en bescherming, deze gids biedt professionals van waardevolle informatie om veilig en efficiënt te werken in diverse werkomgevingen.

ninetails said...

Looking for convenient and professionalgrooming pets near me
? Look no further! Our dedicated team of experienced groomers is here to provide top-notch care for your furry companions. With our convenient location and flexible appointment scheduling, we make it easy for you to keep your pets looking their best. Trust us to deliver a personalized grooming experience that ensures both the comfort and well-being of your beloved pets. Book your appointment today and give your furry friends the pampering they deserve!

Ring Hope said...

Unleash Your Power with Custom Punch Paddles and take your training to the next level. Designed to enhance your speed, precision, and power, these personalized paddles offer a tailored experience to meet your specific needs. Whether you're a beginner or a seasoned pro, custom punch paddles provide the perfect combination of comfort, durability, and performance, allowing you to unleash your full potential and achieve your fitness goals. Elevate your workouts and dominate your training sessions with the ultimate tool for unleashing your power.

alpine bear said...

Elegir la mochilas de viaje perfecta puede marcar la diferencia en tus aventuras. Desde la comodidad de los tirantes hasta la capacidad de almacenamiento y durabilidad, cada detalle cuenta. Descubre cómo seleccionar la mochila ideal que se adapte a tus necesidades y te acompañe en cada paso del camino.

Ring Hope said...


Elevate your karate game to new heights by equipping yourself with a high-quality karate chest protector. This essential piece of gear provides superior protection and peace of mind during intense sparring sessions and competitions. With its durable construction and secure fit, it ensures that your chest remains shielded from potential impacts, allowing you to focus on perfecting your technique and reaching your full potential as a karateka. Enhance your training experience and stay confident in your defense with a top-notch chest protector by your side.

Health & Care aesthetic said...

Awesome Detailed Blog
Try Reaching Out To Us Rhinoplasty in islamabad

Carzilla Auto Services said...

Thanks For Update:

Best Car Garage in Dubai

Pema wangmo said...

I found it very good content so thank you so much. Browse through our diverse selection and find the best wall hanging that resonates with your vision.

Antony said...

I recently completed my first scarf, and I couldn't be more proud of it! With each stitch, I felt a sense of accomplishment and creativity.
New Jersey Federal Criminal Lawyer
Federal Criminal Defense Lawyer

Yozar dorji said...

We appreciate you sharing this useful information with us. You are remarkably skilled at putting up the programme and earning a fortune from writing. You can study from LinkedIn Marketing training in Bangalor to make your life simpler and promote faster growth. There are always new ways to make money.

sonam euden said...

I would like to convey my appreciation for your kind words about the knowledge you provide and your willingness to consider suggestions for personal growth and self-improvement. One way to embark on this journey is by exploring opportunities to revitalize your skin through Maya Medi Spa. They offer a series of "MAYA FLOW - IV TREATMENTS" sessions, scheduled a few weeks apart, designed to provide you with IV hydration that boosts immune function, reduces inflammation, and accelerates muscle recovery. This can facilitate faster recovery from both physical exercise and illnesses.

Carzilla Auto Services said...

Our qualified Porsche Specialists conduct Porsche Standard Repair and Maintenance Techniques at our Dealer Standard Porsche Service Dubai.

Porsche Service in Dubai

sonam euden said...

I wanted to drop by and say thank you from the bottom of my heart. Your support and kindness have made a significant difference in my life. I'm incredibly grateful for your presence and encouragement. 🙌On another note, I'd like to introduce you to a fantastic product that has been a game-changer for me. It's called Buy Friends Wall Art -One with umbrellas - SMEWIndia and it's designed to hang on the wall beautifully. I've personally found it incredibly useful, and I think you'll love it too. If you're interested, I can share more details with you. Please visit https://smewindia.com/ for all kinds of handmade! 😊"

Carzilla Auto Services said...

Nice Post THANKS FOR UPDATE:

Sweet Water Tanker Supply in Dubai

Carzilla Auto Services said...

Welcome to Carzilla Auto Service, your trusted destination for Jaguar, Audi, BMW, and Porsche repair services in Dubai. Our skilled technicians specialize in providing quality repairs for these luxury car brands. Experience excellence in automotive care for your Jaguar, Audi, BMW, or Porsche vehicle. Visit us today for reliable service near you.

Jagaur Ac Repair

Global Degrees said...

It was worth reading your content, thank you for sharing wonderful content, and insisting you to share such valuable content more, If you are searching to study abroad near me Global Degrees is your gateway to pursuing higher education in the United Kingdom. With our comprehensive and student-centered services, we offer a seamless path for international students to achieve their academic aspirations. We provide assistance with university selection, admissions guidance, visa support, and personalized academic counseling.

Global Degrees said...

If you are searching to Study in Canada from Hyderabad Studying in Canada through Global Degrees is not just an educational opportunity; it's a life-changing experience. With their guidance and expertise, you can unlock your potential and immerse yourself in a world-class education system while enjoying the rich cultural tapestry that Canada has to offer.

shofialisa said...

"Adventures in Automation" is a captivating journey into the world of technology and innovation. It's a narrative of exploration, discovery, and problem-solving, where automation takes center stage. From streamlining complex tasks to enhancing efficiency and productivity, these adventures showcase the incredible potential of automation in our rapidly evolving digital landscape.... uncontested divorce virginia beach
uncontested divorce attorneys in virginia beach

Alexander_01 said...

Navigating "The Cheezy Internet" involves crafting Ruby + Watir tests. This dynamic approach to web automation allows developers to efficiently validate functionality and performance on "The-Internet," ensuring a seamless user experience. The synergy of Ruby and Watir simplifies the process, making it an effective strategy for comprehensive testing and quality assurance.This blog is a goldmine of information. Your blog packs a punch in just a few sentences. Your words are like gems. Thank you for sharing this! A quick, delightful read that left me inspired.how to file for divorce in virginia

Global Degrees said...

It was worth reading your content, Please keep on sharing such a wonderful content. Study in Germany from India after 12th Global Degrees serves as the gateway for Indian students to embark on a transformative academic expedition in Germany after completing their 12th grade. The partnership between Global Degrees and German universities fosters an environment where students can thrive academically, culturally, and personally.

Carzilla Auto Services said...

Thanks For Update:

BMW Repair in Dubai

BMW workshop

BMW Service Dubai


BMW Ac Repair

BMW 7 Series Repair

car garage dubai

Health & Care aesthetic said...

I was looking for this topic and I am really grateful that I found this. Try Reaching Out To Us Liposuction In Islamabad

landscape said...

Thanks for sharing such awesome conten with us. it's worth reading. If you take pride in owning a Subaru, you undoubtedly appreciate the charm of this renowned Japanese brand. Subaru’s are celebrated for their exceptional performance, luxurious features, and elegant design. However, like any vehicle, Subaru’s may require replacement parts over time. Whether it’s for routine maintenance or unforeseen repairs, the cost of new OEM (Original Equipment Manufacturer) parts can strain your finances. This is where high-quality Subaru used Parts come into play.

landscape said...

Thanks for sharing sch awesome content. It's worth reading. In the realm of automobiles, Scion emerges as a symbol of style and performance, rivaling even the most renowned names. Scion cars transcend mere transportation; they embody individuality and youthful energy. With sleek designs, advanced technology, and a dedication to customization, Scion vehicles are meticulously crafted to cater to the preferences of today’s driver. Whether navigating city streets or embarking on a road trip, a Scion car ensures a stylish experience. Enhance your Scion’s performance and style with confidence, knowing you can achieve it with high-quality Scion Parts.

Health & Care aesthetic said...

I was looking for this topic and I am really grateful that I found this. Also Know Best Hydrafacial In Islamabad

Mobile App Development said...

Also Know About Natural Language Processing Dubai

Robin said...

Very interesting and different! Thanks for every informative site. abogados divorcio roanoke va

john wolker said...

https://kokozukaufen.de/product/afghanisches-heroin-kaufen/
https://kokozukaufen.de/product/afghanisches-heroin-kaufen/

tamo rene said...

https://originaltforerkort.eu/product/kjop-forerkort-online/
Kjøp et registrert og ekte førerkort online | Führerschein
https://originaltforerkort.eu/product/original-fuhrerschein-kaufen/