Test Assumptions, Not Methods

bdd

Sat Feb 23 16:27:00 -0800 2008

Specs should test assumptions, not methods.

How many specs should there be for each method? One per assumption. For example, this method:

def thumbnail_filename
  "images/thumbs/#{basename}.jpg"
end

…has one assumption, so it needs one spec:

it "stores thumbnail jpegs in the thumbs subdir" do
  @image.should_receive(:basename).and_return("test")
  @image.thumbnail_filename.should == "images/thumbs/test.jpg"
end

But this method:

def popular?
  !archived? and recent_views > 50
end

…has three assumptions:

it "is never considered popular when archived" do
  @item.should_receive(:archived?).and_return(true)
  @item.should_receive(:recent_views).and_return(9999999)
  @item.should_not be_popular
end

it "is not considered popular when there are not many recent views" do
  @item.should_receive(:archived?).and_return(false)
  @item.should_receive(:recent_views).and_return(1)
  @item.should_not be_popular
end

it "is considered popular when there are lots of recent views" do
  @item.should_receive(:archived?).and_return(false)
  @item.should_receive(:recent_views).and_return(1000)
  @item.should be_popular
end