Wednesday, April 8, 2009

More Recipe Helper Specs

‹prev | My Chain | next›

Tonight I try to finish off my recipe helpers.

First up is an example for wikifying kid nicknames. This was partly implemented last night, but I wanted to pull the data from CouchDB rather than from a hard-coded hash lookup. The example I try is:
    it "should lookup kid nicknames" do
RestClient.stub!(:get).and_return('{"marsha":"the oldest Brady girl"}')
wiki("[kid:marsha]").should contain("the oldest Brady girl")
end
I am not testing the CouchDB integration point here in the helper, so I just stub it out. I try to make this example pass with this helper method:
    def wiki(original)
text = original.dup
text.gsub!(/\b(\d+)F/, "\\1° F")
text.gsub!(/\[kid:(\w+)\]/m) { |kid| kid_nicknames[$1] }
text.gsub!(/\[recipe:(\S+)\]/m) { |r| recipe_link($1) }
RedCloth.new(text).to_html
end

def kid_nicknames
@@kid_kicknames ||= JSON.parse(RestClient.get("#{@@db}/kids"))
end
Unfortunately, I get an error due to the @@db class instance variable not being defined:
1)
NameError in 'wiki data stored in CouchDB should lookup kid nicknames in CouchDB'
uninitialized class variable @@db in Eee::Helpers
./helpers.rb:32:in `kid_nicknames'
./helpers.rb:26:in `wiki'
./helpers.rb:26:in `gsub!'
./helpers.rb:26:in `wiki'
./spec/eee_helpers_spec.rb:32:
./spec/eee_helpers_spec.rb:3:
Ick. The @@db instance variable will be available in the running Sinatra application. Since I am testing helpers in isolation, I get a nice failure.

I think that this is telling me that I need to move this code into a separate class (possibly a caching class). But for now, I cheat by adding a stub-able helper method _db. The specification then requires a context to stub out that method:
  context "data stored in CouchDB" do
before(:each) do
self.stub!(:_db).and_return("http://example.org/couchdb")
end

it "should lookup kid nicknames" do
RestClient.stub!(:get).and_return('{"marsha":"the oldest Brady girl"}')
wiki("[kid:marsha]").should contain("the oldest Brady girl")
end
The code implementing this example is then:
    def kid_nicknames
@@kid_kicknames ||= JSON.parse(RestClient.get("#{_db}/kids"))
end

def _db
@@db
end
Finishing the remaining helper specs are relatively trivial after that.
(commit)

No comments:

Post a Comment