Skip to content

Tutorial

jimweirich edited this page Sep 2, 2012 · 8 revisions

RSpec/Given Tutorial

Let's work through an example of using RSpec/Given in a more or less real example. We will use examples from the EverCreft-Kata project by Guy Royse (@guyroyse) and George Walters II (@walterg2).

Character Names

Feature: Create a Character

As a character I want to have a name so that I can be distinguished from other characters

  • can get and set Name

Getting the name.

We will start with just getting the name from a character object.

describe "Character has name" do
  Given(:guy) { Character.new("George") }
  Then { guy.name.should == "George" }
end

This is the simplest possible spec with a single Given clause and a single Then clause. The Given clause specifies that "guy" will refer to an object created by the Character.new call. The Then clause specifies that the "guy" object has a name method that returns "George".

Setting the name

Now let's expand the example to include setting the name.

describe "Character has name" do
  Given(:guy) { Character.new("George") }
  Then { guy.name.should == "George" }

  describe "changing the name" do
    When { guy.name = "Bill" }
    Then { guy.name.should == "Bill" }
  end
end

Nested describe or context blocks inherit the givens (and whens) from the enclosing blocks. So the given "guy" is still available in the nested "changing the name" block.

Clone this wiki locally