👨🏿‍💻
Learn
  • Learn And The Power Of Community
  • Intro
    • learn-co-curriculum/welcome-to-learn-verified
    • learn-co-curriculum/your-first-lab
    • learn-co-curriculum/environment-setup
  • Intro to tic tac toe
    • matz-readme
    • what-is-a-program?
    • hello world
    • Intro to irb
    • Reading-error-messages
    • Data-types
    • variable
    • Variable-assignment lab
    • String interpolation
    • Interpolation-super-power
    • Welcome to tic tac toe
    • Array
    • Tic tac toe board
    • Intro to methods
    • Puts print and return
    • Intro-to-tdd-rspec-and-learn
    • Methods and arguments
    • Say hello (lab)
    • Methods-default-arguments
    • ttt-3-display_board-example
    • ttt-4-display-board-rb
    • Intro-to-cli-applications
    • Greeting-cli
    • cli-applications in Ruby
    • Ruby-gets-input
    • Tic tac toe move
    • Truthiness-in-ruby-readme
    • booleans
    • conditional (if)
    • ttt-6-position-taken
    • ttt-7-valid-move
    • rspec-fizzbuzz
    • Looping-introduction
    • Loop
    • while-and-until-loop
    • Tic Tac Toe Turn lab
    • looping-while-until lab
    • Tic Tac Toe Play Loop (lab)
    • Tic Tac Toe Current Player (lab)
    • Intro to ruby iterators
    • Nested Arrays
    • Boolean Enumerators
    • Search Enumerators
    • Tic Tac Toe Game Status
    • tic-tac-toe
  • OOP tic tac toe
    • intro to oop
    • Intro-to-classes-and-instances
    • Classes-and-instances-lab
    • Instance-methods
    • Instance-methods-lab
    • Object Attributes
    • object-attributes-lab
    • Object Initialization
    • Object-initialize-lab
    • oop barking dog lab
    • Procedural-vs-oop
    • oop tic tac toe
  • Git and github
    • Intro to Version Control
    • Git Repository Basics
    • Git-basics-quiz
    • Forks-and-clones
    • Git Remotes and Github
    • Git Remotes and Github Codealong
    • Thinking Ahead: GitHub as Career Differentiator
    • Github Pull Requests
    • Git Collaboration
    • Git-collaboration-quiz
    • Git Basics Quiz
  • HTML
    • A-quick-tour-of-the-web
    • The-web-is-made-of-strings
    • What-makes-the-web-possible?
    • html-introduction
    • Your first-html-tag-lab
    • Nested-tags-and-attributes
    • Well-formed-html-document-lab
    • HTML elements types overview
    • Researching-HTML-elements
    • Separation-of-content-and-presentation
  • CSS
    • Introduction-to-css
    • introduction-to-css-code-along
  • Procedural Ruby
    • Regex-what-is-a-pattern
    • Regex-basics
    • Regex-lab
    • Regex-match-scan-grep-methods
    • learn-co-curriculum/method-arguments-lab
    • Method-scope
    • Return Values Lab
    • Debugging-with-pry
    • Method-scope-lab
    • Truthiness-code-challenge
    • If Statements Lab
    • Case-statements
    • Case-statements-quiz
    • Logic and Conditionals Quiz
    • Ternary Operators and Statement Modifiers lab
    • Looping Lab
    • looping-quiz
    • learn-co-curriculum/looping-times
    • countdown-to-midnight lab
    • Array introduction
    • Using Arrays
    • Array-CRUD-lab
    • Array-methods
    • Array-methods-lab
    • Square array lab
    • Collect and Return Values
    • Collect Lab
    • Badges and Schedules Lab
    • Oxford comma lab
    • Deli counter lab
    • Reverse Each Word Lab
    • Yield-and-blocks
    • Each Lab
    • Return from Yield Statements
    • My All? Lab
    • My Find Lab
    • Cartoon Collections Lab
    • Enumerators Code Challenge
    • Prime? Lab
    • Sorting
    • Sorting Lab
    • Introduction to Hashes
    • Using Hashes lab
    • Ruby-symbols
    • Hash iteration
    • Hash Iteration Lab
    • Hash Iteration with Collect
    • Intro to Nested Hashes
    • Building Nested Hashes
    • Building Nested Hashes Lab
    • Nested Hash Iteration
    • Nested Hashes Lab
    • Multitype Collections Lab
    • Iterating over Nested Hashes Codealong
    • Other Hashes Codealong
    • Hashes Manipulation Lab
  • OOP Ruby
    • OO Ruby Video: Object Orientation Overview
    • Object Accessors
    • Instance Variables lab
    • Video Review: Object Properties
    • Meowing Cat
    • Intro to Object Orientation - Ruby
    • oo basics lab
    • OO Basics with Class Constants
    • Self
    • OO School Domain lab
    • OO Counting Sentences lab
    • Class Variables and Methods
    • Class Variables and Methods Lab
    • Remembering Objects
    • Puppy Lab
    • Advanced Class Methods
    • Advanced Class Methods Lab
    • Video Review: Object Models
    • OO Email Parser lab
    • OO Anagram Detector lab
    • OO Cash Register lab
    • Intro to Object Relationships
    • Belongs to Object Lab
    • Has Many Object
    • Has Many Object Lab
    • Collaborating Objects Review
    • Collaborating Objects Lab
    • OO My Pets
    • oo kickstarter lab
    • OO Banking lab
    • Has Many Objects Through
    • Has Many Objects Through Lab
    • Intro to Inheritance
    • Intro to Inheritance Lab
    • Super
    • Super Lab
    • Intro to Modules
    • Intro to Modules Lab
    • Mass Assignment
    • Mass Assignment and Metaprogramming
    • Mass Assignment Lab
    • Custom Errors lab
    • OO Triangle lab
  • Scraping and project
    • Gems and Bundler
    • Scraping
    • Scraping Lab
    • Kickstarter Scraping Lab
    • Video Review: Object Orientation and Scraping
    • OO Ruby Object Orientation Video Review
    • Music Library CLI
    • Video Review: Music Library CLI
    • Tic-tac-toe with AI project
    • Student Scraper
    • CLI Data Gem Portfolio Project
    • CLI Data Gem Walkthrough
    • CLI Data Gem Walkthrough: Creating a CLI Scraper Gem
    • Common Anti-Patterns in CLI Data Gem
    • Student Example 1: Refactoring CLI Gem
    • Student Example 2: Refactoring CLI Gem
  • SQL
    • What is SQL
    • SQL Intro and Installation
    • SQL Database Basics
    • SQL Databases and Text Editors
    • SQL Data Types
    • SQL Inserting, Updating, and Selecting
    • Basic SQL Queries
    • SQL Aggregate Functions
    • SQL Aggregate Functions Lab
    • SQL Bear Organizer Lab
    • Edgar Codd and Table Relations
    • Table Relations
    • SQL JOINS
    • SQL Complex Joins
    • SQL Join Tables
    • Grouping and Sorting Data
    • SQL Joins Review Lectures
    • SQL Crowdfunding Lab
    • SQL Library Lab
    • Pokemon Scraper Lab
  • ORM And Active record
    • Why an ORM is Useful
    • Mapping Ruby Classes to Database Tables
    • Mapping Classes to Tables Lab
    • Mapping Database Tables to Ruby Objects
    • Mapping Database Rows to Objects Lab
    • Updating Records in an ORM
    • Updating Records in an ORM Lab
    • Preventing Record Duplication
    • ORMs Lab: Bringing It All Together lab
    • Dynamic ORMs
    • Dynamic ORMs with Inheritance
    • ActiveRecord Mechanics
    • Translating from ORM to ActiveRecord
    • Intro to Rake
    • Mechanics of Migrations
    • Writing Our Own Migrations
    • Migrations and Active Record Lab
    • ActiveRecord CRUD Lab
    • Advanced Finding Lab
    • ActiveRecord Associations
    • ActiveRecord Associations Lab
    • ActiveRecord Associations Lab II
    • ActiveRecord Associations Video Review
    • ActiveRecord Associations Video Review II
    • Video Review: Aliasing ActiveRecord Associations
    • Video Review: Blog CLI with ActiveRecord and Associations
  • Rack
    • How the Internet Works
    • Increasing Layers of Abstraction
    • Inspecting the Web with Rack (lab)
    • The HTTP Request
    • Dynamic URL Routes
    • Dynamic Web Apps with Rack (lab)
    • Rack Responses Lab
    • Rack Routes and GET Params Lab
    • HTTP Status Codes
    • Dynamic URLs and Status Codes Lab
    • Video Review: How The Web Works, Pt 1
    • Video Review: How the Web Works, Pt 2
  • Html
    • How the Web Works
    • Site Planning
    • HTML Fundamentals
    • HTTP Status Codes
    • video review how the web works pt 1
    • How the Web Works, Part 2: Overview
    • Setting Up a New Site
    • Document Structure
    • Text Formatting
    • HTML Tables
    • Html-images
    • HTML Links
    • Html backing-up changes
    • HTML Validation
    • Quiz - HTML Fundamentals
    • Dev Tools Super Power
    • HTML Lists
    • Html issue bot 9000 (lab)
    • HTML Forms and Iframes
    • HTML Map and Contact Form Code-along
    • HTML5 Media
    • HTML5 Video Embed Code-Along
    • HTML5 Semantic Elements
    • HTML5 Semantic Containers Code-along
    • HTML5 Quiz
  • CSS
    • CSS Fundamentals
    • CSS Styling Code Along
    • My Little Rainbow
    • CSS Kitten Wheelbarrow
    • CSS Graffiti Override Lab
    • CSS Issue Bot 9000
    • Your first deployment
    • The Box Model
    • Layout Types
    • Float
    • Clearfix
    • Centering
    • Column Structure
    • CSS Columns Code Along Exercise (lab)
    • Box Model & Page Layout
    • Using Z Index
    • Positioning
    • ZHW Shoes Layout (lab)
    • Zetsy (lab)
    • CSS Box Style Code Along
    • Animal Save (lab)
    • Building Responsive Sites
    • Intro to Responsive Media
    • CSS Media Queries
    • Working with Responsive Type
    • Responsive layout
    • The Viewport Property
    • Responsive Features Code-Along (lab)
    • Bootstrap Introduction
    • Bootstrap Code-Along
    • Bootstrap Grid System
    • Grid Layout Code-Along
    • Bootstrap Navbar Code-Along
  • Sinatra
    • What is Sinatra?
    • Sinatra From Scratch
    • Using the Shotgun Development Server (lab)
    • Sinatra Basics
    • Sinatra Hello World Basics (lab)
    • Routes in Sinatra
    • Sinatra Routes Lab
    • Intro To MVC
    • Sinatra MVC File Structure (lab)
    • Sinatra Views: Using ERB
    • Sinatra Views (lab)
    • Sinatra Basic Views Lab
    • Sinatra Views Lab II
    • Intro To Capybara
    • Dynamic Routes in Sinatra
    • HTML Forms and Params
    • Passing Data Between Views and Controllers in Sinatra
    • Sinatra Forms Lab
    • Sinatra Yield Readme
    • Integrating Models Sinatra Code-along
    • Sinatra MVC Lab - Pig Latinizer
    • Sinatra Basic Forms Lab
    • Sinatra Forms
    • Nested Forms Readme
    • Sinatra Nested Forms Lab: Pirates!
    • Lab Review-- Sinatra Nested Forms Lab: Pirates
    • Sinatra Nested Forms Lab: Superheroes!
    • Sessions and Cookies
    • Mechanics of Sessions
    • Sinatra Basic Sessions Lab
    • Using Sessions
    • Sinatra and Active Record CRUD
    • Sinatra Activerecord Setup
    • Sinatra ActiveRecord CRUD
    • User Authentication in Sinatra
    • Sinatra Sessions Lab - User Logins
    • Securing Passwords
    • Secure Password Lab
    • Sinatra Authentication- Overview
    • RESTful Routes
    • Restful Routes Basic Lab
    • Sinatra ActiveRecord Associations: Join Tables
    • Using Tux in Sinatra with ActiveRecord
    • ActiveRecord Associations in Sinatra
    • Sinatra Multiple Controllers
    • Sinatra and Active Record: Associations and Complex Forms
    • Sinatra Playlister (lab)
    • Welcome to NYC Sinatra! (lab)
    • Building a Site Generator, Part 1- Overview
    • Building a Site Generator, Part 2- Overview
    • Fwitter Group Project
  • Rails
    • Welcome To Rails
      • Rails Application Basics
      • Rails Static Request
      • Rails Hello World Lab
      • Rails Model View Controller
      • Intro to Rails- Overview
    • Intro to REST
    • Active Record Models and Rails
    • ActiveRecord Model Rails Lab
    • RESTful Index Action Lab
    • Rails Dynamic Request
    • Rails Dynamic Request Lab
    • Rails URL Helpers
    • Rails URL Helpers Lab
    • Rails form_tag
    • Rails form_tag Lab
    • Create Action
    • Create Action Lab
    • Index, Show, New, Create Lab
    • Edit/Update Action
    • form_for on Edit
    • Strong Params Basics
    • form_for Lab
    • Rails Generators
    • CRU with form_for Lab
    • Resource and Scaffold Generator
    • Rails Blog scaffold
    • Todo mvc assets and managing lists
    • Rails Forms Overview
    • ActiveRecord Validations
    • ActiveRecord Validations Lab
    • Validations in Controller Actions
    • Validations In Controller Actions Lab
    • Validations with form_tag
    • Validations with form_for
    • DELETE Forms and Requests
    • Testing in Rails
    • Validations with form_tag
    • CRUD With Validations Lab
    • Join the Fun rails
    • Activerecord lifecycle reading
    • Displaying Associations Rails
    • Active Record Associations Review
    • Forms And Basic Associations Rails
    • Forms And Basic Associations Rails Lab
    • Basic Nested Forms
    • Displaying Has Many Through Rails
    • Displaying Has Many Through Rails Lab
    • Has Many Through Forms Rails
    • Has Many Through Forms Rails Labs
    • Has Many Through in Forms Lab Review- Overview
    • Deep Dive into Nested Forms- Overview
    • Layouts And Templates in Rails
    • Rails Layouts And Templates Lab
    • Simple Partials
    • Simple Partials Lab
    • Partials with Locals
    • Partials with Locals
    • Refresher on MVC
    • Refactoring Views With Helpers
    • Refactoring Views With Helpers Lab
    • Model Class Methods
    • Optimal Queries using Active Record (lab)
    • Routing And Nested Resources
    • Nested Resource Routing Lab
    • Modifying Nested Resources
    • Modifying Nested Resources Lab
    • Namespaced Routes
    • Namespaced Routes Lab
    • Todomvc 2 lists have items
    • TodoMVC 3: Mark Items Complete
    • Todomvc 4 refactoring with partials and helpers
    • Todomvc 5 deleting items
    • Introduction to Authentication and Authorization
      • Cookies and sessions
      • Cookies and Sessions Lab
      • Sessions Controller
      • Sessions Controller Lab
      • Login Required Readme
      • Login Required Lab
      • Using has_secure_password
      • Has_secure_password lab
      • Authentication- Overviewn
      • OmniAuth
      • Omniauth Lab
      • Omniauth review lecture in todomvc
      • Authentication and authorization recap and gems
    • Rails Amusement Park lab
    • How to Find Gems
  • JavaScript
    • Intro to JavaScript
      • JavaScript Data Types
      • JavaScript Data Types Quiz
      • JavaScript Variables
      • JavaScript Comparisons
      • Conditionals
      • Logical Operators
      • Functions
      • Intro to Debugging
      • Intro to Testing
      • JavaScript Basics Quiz
    • Scope
      • Scope chain
      • JavaScript Practice Scope Lab
      • Lexical scoping
      • Errors and Stack Traces
      • Hoisting
    • Arrays And Objects
      • Objects
      • JavaScript: Objects and Arrays Quiz
      • Object Iteration
      • JavaScript Logging
      • Traversing Nested Objects
      • Filter
      • Map
    • Functions Revised
      • First-Class Functions Lab
      • First-Class Functions
      • First-Class Functions Practice
      • First-Class Functions Practice Lab
    • OOP
      • Creating Objects
      • Object Methods and Classes
      • Using Prototypes
      • Using Classes in Javascript
      • JavaScript This Walkthrough
      • This Code-along
      • Bind, Call, and Apply Readme
      • Bind, Call, Apply Lab
      • Object Relations
      • Association Methods in Javascript
      • Class Relations Lab
      • JavaScript Closures and Higher Order Functions
      • Closures Lab
      • JavaScript Arrow Functions
      • Daily Lunch Lab
    • DOM
      • Introduction to the DOM
      • Introduction to the DOM Lab
      • More on the DOM
      • Creating and Inserting DOM Nodes
      • The DOM Is a Tree
      • Listening to Nodes
      • Modify HTML With jQuery
      • Modifying HTML Lab
      • jQuery Selectors
      • Document.ready
      • Acting On Events Lab
      • DOM Quiz
    • Templates
      • Introduction to CSS
      • CSS Quiz
      • CSS Libraries
      • CSS Libraries Lab
      • Intro to Templates
      • Template Engines
      • Template Engines Lab
      • Advanced Templating
      • Advanced Templating Lab
    • Asynchronous JavaScript
      • Intro to XHR Code Along
      • Hitting APIs Lab
      • Advanced AJAX Lab
      • AJAX and Callbacks
      • AJAX and Callbacks Lab
      • REST Refresher
      • REST Quiz
      • Fetch
      • JavaScript fetch() Lab
      • Intro to Mocha
      • Testing with Spies
      • Testing with Mocks and Stubs
  • Rails and JavaScript
Powered by GitBook
On this page
  • Objectives
  • A Note on This Guide
  • RSpec - Test Driven Development
  • What is Test Driven Development?
  • Test Driving FizzBuzz
  • Defining Our Expectations
  • Introduction to RSpec
  • describe
  • it
  • expect, to and eq
  • A FizzBuzz Test Suite
  • How to Run an RSpec Test Suite
  • First run rspec via learn
  • Reading RSpec Output
  • Solving FizzBuzz
  • A Bit About Your Test Vs Your Program
  • Continuing to Solve Fizzbuzz
  1. Intro to tic tac toe

rspec-fizzbuzz

Objectives

  1. Build methods that utilize flow control

  2. Read and understand test output to develop a working program

  3. Gain more familiarity with the concept of test driven development

A Note on This Guide

We've been introduced to the concepts of test driven development and reading and understanding RSpec tests before.

Every time you run learn to run a lab's tests, you are running an RSpec test suite - that's how we build labs on Learn.

You've been reading these tests for a while now, but TDD is a big topic and we're going to take a closer look at it here.

You're still not being asked to write your own tests. We're simply aiming to understand the purpose of tests, a bit on the philosophy behind them and a bit more on how to read RSpec tests better.

Remember, when we refer to RSpec or rspec, that is equivalent to running the learn or learn test command, which invokes the Learn test files in spec.

You must have the learn-co gem installed. If you set up your environment through Learn and have used the learn command before (very likely if you've made it this far), you are totally fine. Run learn now to confirm. If you're having trouble or aren't sure, ask a question on Learn!

RSpec - Test Driven Development

RSpec is a testing tool for the Ruby programming language. Born under the banner of Behavior-Driven Development, it is designed to make Test-Driven Development a productive and enjoyable experience. The learn gem wraps rspec with additional functionality, so if you've been using learn, you've been using rspec.

What is Test Driven Development?

Test Driven Development, or TDD, is a method for approaching a problem not through the implementation of the solution, but rather, through the expectations of a working solution. What that means is, instead of trying to write the code that solves the problem, you first define what the working code will do when it works, and then you write the implementation to make it work.

Test Driving FizzBuzz

The goal of FizzBuzz is to build a program that can take a number and if the number is evenly divisible by 3, it should return "Fizz", if it's divisible by 5, it should return "Buzz", and if it's divisible by both 3 and 5, it should return "FizzBuzz".

Defining Our Expectations

Let's approach solving this problem from a TDD approach. That means that we don't care about "how", but rather, we care about "what". What should the program do if it works correctly, not how it does it. We are going to write our expectations first, then our implementation.

Before we look at the RSpec syntax, let's just express our tests in plain English (also sometimes referred to as "pseudo-code").

  1. We expect fizzbuzz(3) to return "Fizz"

  2. We expect fizzbuzz(5) to return "Buzz"

  3. We expect fizzbuzz(15) to return "FizzBuzz"

Furthermore, we could also provide a negative case.

  1. We expect fizzbuzz(4) to return nil.

We don't care how that #fizzbuzz method works, nor how it's defined, we are just stating our expectations. And we're doing that first. When coding, it's important to have a target to shoot for; by writing your test first and stating your expectations of your code, you know your goal. You get to use your entire brain to think about just your goals, not how you'll get there, which adds clarity and focus to the problem.

The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility.

— Edsger W. Dijkstra

Test-Driven Development allows us to fully utilize our mental capacity to clearly state the problem we're solving and then to 100% focus on implementing a solution. When you are just coding, you're actually focusing on stating the problem and the solution at the same time. You are thereby splitting your thinking in two, making you less effective at both.

It's the exact same reason you make a todo list. Also testing is not for present you, it's for future you.

— Joe M Burgess

Introduction to RSpec

RSpec is what's known as a DSL, or Domain Specific Language (also called a "Task Oriented Language" - a language designed for a specific kind of problem). It's a set of vocabulary (but actually just methods) that is useful for completing a specific kind of task. In this example, that task is describing our expectations and tests.

Here is an example of an RSpec test for one of the expectations above:

describe "fizzbuzz" do
  it 'returns "Fizz" when the number is divisible by 3' do
    fizz_3 = fizzbuzz(3)

    expect(fizz_3).to eq("Fizz")
  end
end

Sure, that code looks crazy and it's actually quite advanced, but we don't need to think about all of it, we just need to focus on 5 words: describe, it, expect, to, and eq. Let's break down that example.

describe

The first thing RSpec allows you to do with its DSL is to define what it is you are describing. As in, are we writing a test that describes how our Billing System works or are we writing a test that describes how #fizzbuzz works?

RSpec gives us the describe method. The argument we pass to the describe method is arbitrary; it doesn't really do anything besides document what exactly it is we're testing. Since we're writing a specification (a test) for #fizzbuzz, it makes sense to pass describe the string "fizzbuzz". describe also accepts a block, which will be covered shortly, but for now, just know that a block in Ruby starts with the do keyword. Every block that is opened must be closed. We use the end keyword to close the describe block.

The describe block can be thought of as a template for a spec (a test).

describe "The Thing We're Testing" do
  # Specifications, that is, specific test examples, go here.
end

So, what is a block?

A block is a simple unit of code that starts with the do keyword and ends with the end keyword. Blocks are a complex and wonderful part of the Ruby language and we don't need to focus on exactly what they are right now. It's best to think of a block just as a word used to describe a certain chunk, or unit, of code (almost like a paragraph). You can generally tell that something is a block because it is indented and grouped together. The aesthetics, the very form of the code, like in a poem, suggest a structure. That's a block.

Resources on Blocks:

it

Now that we've created a structure to group our tests together using the describe method, we can move on to actually describing the desired functionality. Every specification in RSpec begins with the it method.

The it method, like the describe method, accepts an arbitrary string as an argument, namely, some text that says what we're currently interested in testing. Like all things in code, every it should be specifying one, only one, and exactly one, desired outcome or behavior.

Above we said that one functionality of #fizzbuzz is that it returns "Fizz" if the number is divisible by 3. So we can simply write that. It's totally up to you, the programmer, to decide the phrasing for your it specification, but a good starting point is a verb or action. it returns or it prints or it emails or it validates etc.

Also like the describe method, the it method accepts a block, beginning with the do keyword and ending with the end keyword, that will encapsulate, or group, the code that will test our expectation.

The it block template might look something like:

it 'returns "Fizz" when the number is divisible by 3' do
  # Code that actually does what we're testing and confirms the desired result
end

So far, if we think of our RSpec test as a form of documentation, we can imagine it might read something like:

fizzbuzz
  returns "Fizz" when the number is divisible by 3

We're simply restating the problem and our expectations in the RSpec DSL. Now let's actually write the test for the specific example.

expect, to and eq

Okay, let's refocus. Our goal is to test that when we call the #fizzbuzz method (which we are yet to build) and pass it the number 3, we expect it to equal "Fizz" if our code works correctly.

Outside of the context of our test suite, we could write an expression like:

That is to say, when we evoke fizzbuzz(3), it should equal "Fizz". Taking advantage of the RSpec DSL, we can express that assertion as follows:

# First, get the return value from fizzbuzz(3), store it in a variable, fizz_3
fizz_3 = fizzbuzz(3)

# Next, our expectation that the value of fizz_3 should be "Fizz"
expect(fizz_3).to eq("Fizz")

So three new RSpec methods, expect, to, and eq.

expect() is a method that accepts our unknown value or variable, the thing we're testing. So for instance, in a simple math equation, imagine the following:

Since x is the unknown variable, we'd be testing the expectation of the value of x, so we pass that value to the expect method. I can imagine it's weird to think of the variable x as an unknown value worth confirming. You're thinking, "It's obviously 2!" But the truth is, you're making the assumption that Ruby has a correct notion of arithmetic. As our programs become more complex and we use more variables, it's very important to constantly validate our assumptions with expectations and testing. Let's finish the example.

In addition to the expect(x) call, we need to communicate what we expect x to be equal to. To accomplish this, we chain a to() method to the expect(), so it simply looks like:

Then finally we use what is known as a matcher, eq, to specify our expectation: that we expect the value of x, passed to the expect method, to equal (to eq) 2.

x = 1 + 1
expect(x).to eq(2)

You won't have to write your own tests for a while, so don't worry about mastering the expect, to, and eq usage. The important part is that you can read the DSL and understand what it is trying to suggest.

A FizzBuzz Test Suite

First, fork and clone this lab and open it on your machine. Read the remainder of this tutorial and follow along by executing certain commands and writing certain code in this lab on your computer.

So the entire FizzBuzz test looks like this:

File: spec/fizzbuzz_spec.rb

require_relative './spec_helper.rb'

describe "fizzbuzz" do
  it 'returns "Fizz" when the number is divisible by 3' do
    fizz_3 = fizzbuzz(3)

    expect(fizz_3).to eq("Fizz")
  end
  it 'returns "Buzz" when the number is divisible by 5' do
    fizz_5 = fizzbuzz(5)

    expect(fizz_5).to eq("Buzz")
  end
  it 'returns "FizzBuzz" when the number is divisible by 3 and 5' do
    fizz_15 = fizzbuzz(15)

    expect(fizz_15).to eq("FizzBuzz")
  end
  it 'returns nil when the number is not divisible by 3 or 5' do
    fizz_4 = fizzbuzz(4)

    expect(fizz_4).to eq(nil)
  end
end

Remember, your goal here is not to be able to write that test suite, yet. Your goal, rather, is to understand what that test suite is describing about your code, about your solution. When I read that, I think the following things:

  1. I need a method called #fizzbuzz that accepts one argument.

  2. When I call that method and pass it a number divisible by 3, like the number 3 for instance, that method should return the string "Fizz".

  3. When I call that method and pass it a number divisible by 5, like the number 5 for instance, that method should return the string "Buzz".

  4. When I call that method and pass it a number divisible by 3 and 5, like the number 15 for instance, that method should return the string "FizzBuzz".

  5. When I call that method and pass it a number not divisible by 3 or 5, like the number 4 for instance, that method should return nil.

How to Run an RSpec Test Suite

First run rspec via learn

Now, from within the directory of this file, type the learn command. Your terminal should have an output that looks something like this:

fizzbuzz
  returns "Fizz" when the number is divisible by 3 (FAILED - 1)
  returns "Buzz" when the number is divisible by 5 (FAILED - 2)
  returns "FizzBuzz" when the number is divisible by 3 and 5 (FAILED - 3)
  returns nil when the number is not divisible by 3 or 5 (FAILED - 4)

Failures:

  1) fizzbuzz returns "Fizz" when the number is divisible by 3
     Failure/Error: fizz_3 = fizzbuzz(3)

     NoMethodError:
       undefined method `fizzbuzz' for #<RSpec::ExampleGroups::Fizzbuzz:0x007f994ac67600>
     # ./spec/fizzbuzz_spec.rb:5:in `block (2 levels) in <top (required)>'

  2) fizzbuzz returns "Buzz" when the number is divisible by 5
     Failure/Error: fizz_5 = fizzbuzz(5)

     NoMethodError:
       undefined method `fizzbuzz' for #<RSpec::ExampleGroups::Fizzbuzz:0x007f994ac65940>
     # ./spec/fizzbuzz_spec.rb:10:in `block (2 levels) in <top (required)>'

  3) fizzbuzz returns "FizzBuzz" when the number is divisible by 3 and 5
     Failure/Error: fizz_15 = fizzbuzz(15)

     NoMethodError:
       undefined method `fizzbuzz' for #<RSpec::ExampleGroups::Fizzbuzz:0x007f994ac64310>
     # ./spec/fizzbuzz_spec.rb:15:in `block (2 levels) in <top (required)>'

  4) fizzbuzz returns nil when the number is not divisible by 3 or 5
     Failure/Error: fizz_4 = fizzbuzz(4)

     NoMethodError:
       undefined method `fizzbuzz' for #<RSpec::ExampleGroups::Fizzbuzz:0x007f994ac5ed20>
     # ./spec/fizzbuzz_spec.rb:20:in `block (2 levels) in <top (required)>'

Finished in 0.00236 seconds (files took 0.39876 seconds to load)
4 examples, 4 failures

Failed examples:

rspec ./spec/fizzbuzz_spec.rb:4 # fizzbuzz returns "Fizz" when the number is divisible by 3
rspec ./spec/fizzbuzz_spec.rb:9 # fizzbuzz returns "Buzz" when the number is divisible by 5
rspec ./spec/fizzbuzz_spec.rb:14 # fizzbuzz returns "FizzBuzz" when the number is divisible by 3 and 5
rspec ./spec/fizzbuzz_spec.rb:19 # fizzbuzz returns nil when the number is not divisible by 3 or 5

When we installed the RSpec and Learn.co gems, we got the learn command. When you type learn and press enter, you are running your test suite — not your program. We haven't even written our FizzBuzz program yet.

So how does that work?

When we run the learn command, in a nutshell, here is what happens:

  1. RSpec looks in a directory named spec for all files that end with the pattern _spec.rb. Why the spec folder and the _spec.rb pattern? No reason, just convention.

  2. RSpec then executes the Ruby code within each _spec.rb file.

  3. During that execution, RSpec pays attention to the results of each test and prints out a nice summary of what happened (which is the output above that we're going to dissect in a minute).

In the spec directory for this lab, there are 2 files: spec_helper.rb, which does not match the pattern of ending with a _spec.rb, and fizzbuzz_spec.rb, which does. So RSpec will open the second file and have Ruby execute it.

If you look at spec/fizzbuzz_spec.rb, there's only 1 line of it that we haven't covered: require_relative './spec_helper.rb'. All this line does is tell Ruby to load the contents of the neighboring file, specified by the starting . (meaning the current directory), and the file name: spec_helper.rb. If you look within spec_helper.rb, you'll see that it's basically configuring how RSpec should run and at this point is totally unimportant. One thing to note, though, is if we need to have our actual test file load any other file, that require_relative line becomes even more interesting.

Again, the learn command wraps RSpec and provides some default options (namely, --format documentation, which controls how your test results print), and, though you will see approximately the same output with rspec or learn, we recommend using learn.

Reading RSpec Output

Let's look at the output RSpec gives us (just run learn again), and dig into it a bit.

Test Run Summary

rspec
Run options: include {:focus=>true}

All examples were filtered out; ignoring {:focus=>true}

fizzbuzz
  returns "Fizz" when the number is divisible by 3 (FAILED - 1)
  returns "Buzz" when the number is divisible by 5 (FAILED - 2)
  returns "FizzBuzz" when the number is divisible by 3 and 5 (FAILED - 3)
  returns nil when the number is not divisible by 3 or 5 (FAILED - 4)

The first two lines of output are descriptive; RSpec is simply telling us what it did.

The lines that follow are important, each line represents a failure. As the test suite runs, RSpec will spit out red text line for every failed expectation (every it block). RSpec will also spit out lines with green text for every passing test.

Programming is a movement from a broken state to a working state. That means you spend the majority of your time with things being broken. Hell, if it worked, you'd be done programming.

If you're new to programming, you're probably used to things working. So when they are broken, it's scary. In programming, you have to feel the exact opposite way. It is totally normal for everything to be broken. As you code, you fix things, one by one, and then, when it all works, you're done for the day.

Reading a Specific Example Failure

So, sure, we know philosophically that the reason why our tests are failing is because we did nothing to make them pass. But what, specifically, is the reason they are failing?

Our rspec output continues with a summary of each individual failure:

Failures:

  1) fizzbuzz returns "Fizz" when the number is divisible by 3
     Failure/Error: fizz_3 = fizzbuzz(3)

     NoMethodError:
       undefined method `fizzbuzz' for #<RSpec::Core::ExampleGroup::Nested_1:0x007fbdd2230428>
     # ./spec/fizzbuzz_spec.rb:5:in `block (2 levels) in <top (required)>'

In the failure output, the first line fizzbuzz returns "Fizz" when the number is divisible by 3 tells us the description of the test. The second line Failure/Error: fizz_3 = fizzbuzz(3) tells us the line that caused the failure or error. In this case, it is an error, and we see the Ruby error.

NoMethodError:
       undefined method `fizzbuzz' for #<RSpec::Core::ExampleGroup::Nested_1:0x007fbdd2230428>
     # ./spec/fizzbuzz_spec.rb:5:in `block (2 levels) in <top (required)>'

We have a NoMethodError. There is no method #fizzbuzz, and the line that is important is line 5 of /spec/fizzbuzz_spec.rb. The rest of it is just RSpec noise (the thing about RSpec::Core::ExampleGroup::Nested_1 is pretty meta and not worth going into here).

So, why did our test fail? Because we did not define a #fizzbuzz method.

Solving FizzBuzz

It is finally time to actually program a solution to FizzBuzz. The first question to answer is where to put our solution, the actual code we care about, the program we're writing. Let's look at our current directory structure:

rspec-fizzbuzz/
    .bundle/
      config
    spec/
        fizzbuzz_spec.rb
        spec_helper.rb
    .learn
    .rspec
    CONTRIBUTING.md
    fizzbuzz.rb
    Gemfile
    Gemfile.lock
    LICENSE.md
    README.md  

The spec directory is for our tests. There's a more advanced folder structure to separate the different kinds of tests you might encounter: unit, acceptance, etc. For now, while our scripts are simple, we'll typically have one _spec.rb test for each lab.

We're not going to put the heart of our application in the spec folder — that wouldn't make sense. We want to keep our code organized so developers can easily guess the context or part of the system a file corresponds to. It's a measure of symmetry to our code for tests to go in the spec directory.

In a larger program, I would put my code in a lib directory. In this example, fizzbuzz.rb is in the root directory, right alongside this README.md.

fizzbuzz.rb is where we're going to code the core of our program: a simple method, #fizzbuzz, that, when invoked by the tests above, will behave as we specified. For now though, let's just fix the first rspec failure.

The first failure is that there is no method known as #fizzbuzz. Let's simply define that method.

File: fizzbuzz.rb

Now, when we run learn, we should expect to see a new sort of error.

A Bit About Your Test Vs Your Program

Run: learn

  1) fizzbuzz returns "Fizz" when the number is divisible by 3
     Failure/Error: fizz_3 = fizzbuzz(3)

     NoMethodError:
       undefined method `fizzbuzz' for #<RSpec::Core::ExampleGroup::Nested_1:0x007fd2f21083b8>
     # ./spec/fizzbuzz_spec.rb:5:in `block (2 levels) in <top (required)>'

Don't panic! It's the same exact failure, our old friend NoMethodError, as though we never defined #fizzbuzz. But look, after all this, we finally did some work and added a clearly defined #fizzbuzz method to fizzbuzz.rb. So why is the test still complaining?

Let's try loading a Ruby environment from within our project directory and playing with the #fizzbuzz method ourselves for a second.

From within rspec-fizzbuzz-v-000, fire up irb, the Interactive Ruby Shell, a real-time Ruby prompt for executing arbitrary code. For instance:

// ♥ irb
2.2.3 :001 > 1+1
 => 2

From within your new IRB shell, try calling the #fizzbuzz method that's defined in fizzbuzz.rb:

// ♥ irb
2.2.3 :001 > fizzbuzz
NameError: undefined local variable or method `fizzbuzz' for main:Object
	from (irb):1
	from /Users/avi/.rvm/rubies/ruby-2.2.3/bin/irb:11:in `<main>'

There's our error. We tried calling #fizzbuzz and IRB complains that it doesn't know what we're talking about. Why? Well, when did we tell IRB to actually load the contents of fizzbuzz.rb? We didn't. Similarly, nowhere in our test runtime did we tell RSpec to actually load the contents of, read, or require fizzbuzz.rb. Try this in IRB:

// ♥ irb
2.2.3 :001 > require './fizzbuzz.rb'
 => true
2.2.3 :002 > fizzbuzz
 => nil

As you can see, by requiring the fizzbuzz.rb file, we were able to call the #fizzbuzz method.

Let's add that requirement to our RSpec test suite, so that our tests know to load the code they're supposed to be testing.

Edit: spec/fizzbuzz_spec.rb

require_relative './spec_helper.rb'
require_relative '../fizzbuzz.rb'

Now we're telling fizzbuzz_spec.rb to load both spec_helper.rb and fizzbuzz.rb.

Run the test suite one more time with learn. You should see failures in line with the following:

  1) fizzbuzz returns "Fizz" when the number is divisible by 3
     Failure/Error: fizz_3 = fizzbuzz(3)

     ArgumentError:
       wrong number of arguments (1 for 0)
     # ./fizzbuzz.rb:1:in `fizzbuzz'
     # ./spec/fizzbuzz_spec.rb:6:in `block (2 levels) in <top (required)>'

Read that error message; it's brand new! Getting a new error message is a sign of progress. It's one more hint the computer is giving you, one more clue to drive your investigation forward. Now it's complaining that our tests are calling the #fizzbuzz method with an argument; however, our definition of #fizzbuzz accepts no arguments. You'll fix that next, but it's important to realize our test suite is now wired up correctly. We can continue building out our #fizzbuzz method and running our specs against that code until we have it working.

Continuing to Solve Fizzbuzz

That's the end of the tutorial part of this lab. You know enough about RSpec and Ruby to continue solving this in a test-driven manner. As you define your #fizzbuzz method, remember that you can always play with it in IRB. For instance, load an IRB terminal and try (line by line):

def fizzbuzz(int)
  if int % 3 == 0 # if the number int is divisible by 3
    "Fizz" # Go fizz
  end
end

fizzbuzz(3) # => You should see a return of "Fizz"
fizzbuzz(5) # => You should see a return of nil
fizzbuzz()  # => You should get an ArgumentError

Helpful Tip: You can try out code in IRB and then copy it to your program files as you get it working. You can also use Pry, an IRB alternative, by placing the line require 'pry' at the top of fizzbuzz.rb and placing binding.pry inside the method before running RSpec.

Good luck!

Previousttt-7-valid-moveNextLooping-introduction

Last updated 5 years ago

A classic programming problem is . It is considered the of programming because there are so many different ways to play it and everyone plays it.

Right now, the entire test suite is failing, which makes sense. We haven't written any code! That's an important point, and I think said it best:

View on Learn.co and start learning to code for free.

FizzBuzz
Stairway to Heaven
Why's Guide to Blocks
Codecademy on Blocks
RubyMonk on Blocks
Steve Klabnik
RSpec Fizzbuzz