This blog no longer exists.
You will be redirected to something cool.

Tuesday, May 10, 2011

RSpec is really, really awesome

Tonight I found out that RSpec is coding zen. For real! It was the first time I'd written my specs BEFORE the code (like you're sposed' to) and it just made my job a LOT easier. Here's what happened:

I wrote the specs:
describe "#make_urls" do
  it "should replace /s with a +" do
    make_urls(["oranges apples"]).should == ["oranges+apples"]
  end
end

While I was writing the code, I'd accidentally used a method for string on an array. Upon testing the code, I couldn't, for the life of me, figure it out. Back in the day when I didn't use RSpec (last week) I'd be shutting down and restarting the Sinatra do-hicky and going back and forth to 192.168.1.more_ip:4567/get_page. However, with RSpec, I was able to tell right away that my code wasn't working. Magic! I'm sold on it.

I accidentally did this:
def make_urls(arr)
  arr.gsub(" ", "+")
end

Instead of this:
def make_urls(arr)
  arr.each do |e|
    e.gsub!(" ", "+")
  end
end

2 comments:

def make_urls(arr)
arr.map { |e| e.gsub(' ', '+') }
end

This also does not replace spaces in-place, which might or might not be what you want it to do.

In fact, if you are trying to escape URLs, maybe URI#escape is what you are looking for, instead of gsub-ing. Like

def make_urls(arr)
arr.map { |e| URI.escape(e) }
end

Since you require open-uri anyway, might as well use URI. ;-D