Thu22Jul

  1. A Tasty RSpec Morsel

    RSpec’s let method is not hugely known but it’s very useful for DRYing up one’s specs. It accepts a symbol and a lazily evaluated block that defines a method when the method name is called

    let(:foo) { puts 'METAPROGRAMMING FTW!' }

    Even less known is that due to way Ruby (< 1.9)  works under the covers, one can pass in block variables and have the method magically accept arguments when it’s called.

    I used this at work to stub out different API responses, and I came up with this little piece of sugar

    let(:api_stub) { |code,response| FakeWeb.register_uri :get, %r|#{API_ENDPOINT}|, :status => [code, response] }
    
    # Usage:
    api_stub '401', 'Unauthorized'
    

    Yum!