« Back to Index

RSpec Template

View original Gist on GitHub

RSpec.rb

describe Stack do
  context "Upon Creation" do
    let(:stack) { Stack.new } # `let` creates a lazy loaded (and memoized) helper method
    
    it "will be empty" do
      stack.should be_empty # `stack` is still called when using the `should` assertion
    end

    it "will raise underflow if popped" do
      lambda { stack.pop }.should raise_error(Underflow)
    end
  end
end

$count = 0
describe "let" do
  let(:count) { $count += 1 }

  it "memoizes the value" do
    count.should == 1
    count.should == 1 # notice even though we call `count` again, the value is cached so it's still == one
  end

  it "is not cached across examples" do
    count.should == 2 # but across tests the value can be updated
  end
end