Slides

RSpec Explained

describe

    describe Cookie do
    end
  • defines a context
  • takes a class or a string as its name

it

describe Cookie do
  it "tastes yummy" do
  end
end
  • defines an example
    • (aka spec or test)
  • takes a string as its name

should

describe Cookie do
  it "tastes yummy" do
    cookie = Cookie.new
    cookie.chips.should == 72
  end
end
  • defines an assertion
  • every test needs at least one assertion
    • or else you're not really testing anything

matchers

describe Cookie do
  it "has approximately 70 chips" do
    cookie = Cookie.new
    cookie.chips.should be_within(5).of(70)
  end
end

be matchers

[].should be_empty
  • uses method_missing magic
  • be_empty invokes empty? on its target
  • be_valid invokes valid? on its target
  • and so on

before and after

describe Counter do
  before do
    @data = [0,1,2,3]
  end
  it "counts data" do
    Counter.new(@data).count.should == 4
  end
  it "adds data too" do
    Counter.new(@data).sum.should == 6
  end
end
  • before blocks will be executed before each of the specs in that describe block
  • there's also before :all do..end which executes only once
  • there's also after with similar semantics

let

describe Counter do

  let(:data) { [0,1,2,3] }

  it "counts data" do
    Counter.new(data).count.should == 4
  end
  it "adds data too" do
    Counter.new(data).sum.should == 6
  end
end

subject

describe Counter do
  let(:data) { [0,1,2,3] }

  subject { Counter.new(data) }

  it { should be_a(Counter) }

  it { should_not be_nil }

  it "counts data" do
    subject.count.should == 4
  end

  it "adds data"do
    subject.sum.should == 6
  end

end

more