Skip to content

Instantly share code, notes, and snippets.

@bbasata
Created November 5, 2011 02:04

Revisions

  1. bbasata created this gist Nov 5, 2011.
    27 changes: 27 additions & 0 deletions factorial_spec.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    class Integer
    def factorial
    raise if self < 0
    self > 0 ? (1..self).reduce(&:*) : 1
    end
    end

    describe Integer, '#factorial' do
    context "for values larger than 1" do
    example { 2.factorial.should == 2*1 }
    example { 3.factorial.should == 3*2*1 }
    example { 4.factorial.should == 4*3*2*1 }
    example { 8.factorial.should == 8*7*6*5*4*3*2*1 }
    end

    context "for 1" do
    example { 1.factorial.should == 1 }
    end

    context "for 0" do
    example { 0.factorial.should == 1 }
    end

    context "for negative numbers" do
    example { expect { -1.factorial }.to raise_error }
    end
    end