Showing posts with label outside-in. Show all posts
Showing posts with label outside-in. Show all posts

Thursday, October 1, 2009

Ingredients, in Batches

‹prev | My Chain | next›

Picking back up with my ingredient index:
  it "should link to the recipes" do
render("/views/ingredients.haml")
response.should have_selector("a", :count => 3)
end
The expectation that there should be three links in the output comes from the setup block. There are two recipes, one of which appears under two different ingredients in the index:
  before(:each) do
@ingredients = [{'butter' =>
[
['recipe-id-1', 'title 1'],
['recipe-id-2', 'title 2']
]
},
{'sugar' =>
[
['recipe-id-2', 'title 2']
]
}]
end
When I run the spec, this latest example fails:
jaynestown% spec ./spec/views/ingredients.haml_spec.rb -cfs

ingredients.haml
- should have a list of ingredients
- should have a list of recipes using the ingredients
- should link to the recipes (FAILED - 1)

1)
'ingredients.haml should link to the recipes' FAILED
expected following output to contain a <a/> tag:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<p>
<span class="ingredient">
butter
</span>
<span class="recipes">
title 1, title 2
</span>
</p>
<p>
<span class="ingredient">
sugar
</span>
<span class="recipes">
title 2
</span>
</p>
butterrecipe-id-1title 1recipe-id-2title 2sugarrecipe-id-2title 2
</body></html>

./spec/views/ingredients.haml_spec.rb:30:

Finished in 0.03 seconds

3 examples, 1 failure
To get the 3 links (and make the example pass), I add links to the Haml template:
= @ingredients.each do |ingredient|
%p
%span.ingredient
= ingredient.keys.first
%span.recipes
= ingredient.values.first.map{|recipe| %Q|<a href="">#{recipe[1]}</a>|}.join(", ")
Easy enough, but the href attribute is empty. To drive that, I will focus on one recipe, one context:
  context "an ingredient is used in only one recipe" do
it "should have one link to that recipe" do
render("/views/ingredients.haml")
response.should have_selector("a",
:href => "/recipes/recipe-id-1",
:content => "title 1",
:count => 1)
end
end
For good measure, I also describe the case of multiple recipes sharing a recipe:
  context "an ingredient is used in multiple recipes" do
it "should have multiple links to that recipe" do
render("/views/ingredients.haml")
response.should have_selector("a",
:href => "/recipes/recipe-id-2",
:content => "title 2",
:count => 2)
end
end
Adding the hyperlink to the <a> in the Haml templaate:
      = ingredient.values.first.map{|recipe| %Q|<a href="/recipes/#{recipe[0]}">#{recipe[1]}</a>|}.join(", ")
Makes all examples pass:
jaynestown% spec ./spec/views/ingredients.haml_spec.rb -cfs

ingredients.haml
- should have a list of ingredients
- should have a list of recipes using the ingredients
- should link to the recipes

ingredients.haml an ingredient is used in only one recipe
- should have one link to that recipe

ingredients.haml an ingredient is used in multiple recipes
- should have one link to that recipe

Finished in 0.02 seconds

5 examples, 0 failures
The last thing that needs to go on this page are two columns. In the legacy site, we found that the index looked best with two columns:



I write two, paired examples for this output behavior:
  it "should put half of the ingredients in the first column" do
render("/views/ingredients.haml")
response.should have_selector(".col1", :content => "butter")
end

it "should put the other half of the ingredients in the second column" do
render("/views/ingredients.haml")
response.should have_selector(".col2", :content => "sugar")
end
I can make that pass with a table (for the two columns) and batching the ingredients into two:
%table
%tr
- col = 0
- @ingredients.each_slice((@ingredients.size.to_f/2).round) do |batch|
- col = col + 1
%td{:class => "col#{col}"}
= batch.each do |ingredient|
...
I dislike using accumulators (col), but there is no each_slice_with_index in Enumerator, so...

With that, I am done with my inside code work on this mini-feature. Tomorrow, I will work my way back out to the Cucumber scenario to verify that all the pieces work when put together.

Wednesday, September 30, 2009

Outside-In Ingredients

‹prev | My Chain | next›

Running the Cucumber scenario from yesterday, I find that all of the steps are currently undefined:
jaynestown% cucumber features/ingredient_index.feature:7 -s
Sinatra::Test is deprecated; use Rack::Test instead.
Feature: Ingredient index for recipes

As a user curious about ingredients or recipes
I want to see a list of ingredients
So that I can see a sample of recipes in the cookbook using a particular ingredient

Scenario: A couple of recipes sharing an ingredient
Given a "Cookie" recipe with "butter" and "chocolate chips"
And a "Pancake" recipe with "flour" and "chocolate chips"
When I visit the ingredients page
Then I should see the "chocolate chips" ingredient
And "chocolate chips" recipes should include "Cookie" and "Pancake"
And I should see the "flour" ingredient
And "flour" recipes should include only "Pancake"

1 scenario (1 undefined)
7 steps (7 undefined)
0m0.540s

You can implement step definitions for undefined steps with these snippets:

Given /^a "([^\"]*)" recipe with "([^\"]*)" and "([^\"]*)"$/ do |arg1, arg2, arg3|
pending
end

When /^I visit the ingredients page$/ do
pending
end

...
The first two steps in that scenario can be defined with:
Given /^a "([^\"]*)" recipe with "([^\"]*)" and "([^\"]*)"$/ do |title, ing1, ing2|
date = Date.new(2009, 9, 30)
permalink = date.to_s + "-" + title.downcase.gsub(/\W/, '-')

recipe = {
:title => title,
:type => 'Recipe',
:published => true,
:date => date,
:preparations => [{'ingredient' => {'name' => ing1}},
{'ingredient' => {'name' => ing2}}]
}

RestClient.put "#{@@db}/#{permalink}",
recipe.to_json,
:content_type => 'application/json'
end
Nothing too difficult in there—build a hash describing the recipe and then putting into the CouchDB database.

Next, I define the step to visit the ingredient index page that I created yesterday:
When /^I visit the ingredients page$/ do
visit "/ingredients"
end
Easy enough. Except:
jaynestown% cucumber features/ingredient_index.feature
Sinatra::Test is deprecated; use Rack::Test instead.
Feature: Ingredient index for recipes

As a user curious about ingredients or recipes
I want to see a list of ingredients
So that I can see a sample of recipes in the cookbook using a particular ingredient

Scenario: A couple of recipes sharing an ingredient # features/ingredient_index.feature:7
Given a "Cookie" recipe with "butter" and "chocolate chips" # features/step_definitions/ingredient_index.rb:1
And a "Pancake" recipe with "flour" and "chocolate chips" # features/step_definitions/ingredient_index.rb:1
When I visit the ingredients page # features/step_definitions/ingredient_index.rb:22
Resource not found (RestClient::ResourceNotFound)
/usr/lib/ruby/1.8/net/http.rb:543:in `start'
./features/support/../../eee.rb:227:in `GET /ingredients'
(eval):7:in `get'
features/ingredient_index.feature:11:in `When I visit the ingredients page'
Then I should see the "chocolate chips" ingredient # features/ingredient_index.feature:12
And "chocolate chips" recipes should include "Cookie" and "Pancake" # features/ingredient_index.feature:13
And I should see the "flour" ingredient # features/ingredient_index.feature:14
And "flour" recipes should include only "Pancake" # features/ingredient_index.feature:15
Ah, the RestClient::ResourceNotFound exception is being raised because I have not put the CouchDB map/reduce required by the Sinatra action:
get '/ingredients' do
url = "#{@@db}/_design/recipes/_view/by_ingredients?group=true"
data = RestClient.get url
@ingredients = JSON.parse(data)['rows']

"<title>EEE Cooks: Ingredient Index</title>"
end
I am using the couch_docs gem to load design documents into the CouchDB test database, so all I need to do is create couch/_design/recipes/views/by_ingredients/map.js:
function (doc) {
if (doc['published']) {
for (var i in doc['preparations']) {
var ingredient = doc['preparations'][i]['ingredient']['name'];
var value = [doc['_id'], doc['title']];
emit(ingredient, {"id":doc['_id'],"title":doc['title']});
}
}
}
And couch/_design/recipes/views/by_ingredients/reduce.js:
function(keys, values, rereduce) {
if (rereduce) {
var ret = [];
for (var i=0; i<values.length; i++) {
ret = ret.concat(values[i]);
}
return ret;
}
else {
return values;
}
}
With that, I have the first three steps in this scenario passing. That means it is time to work my way into the code to start implementing the next step. The Sinatra action is already done (yesterday), so it is time to start on the Haml template:
describe "ingredients.haml" do
#...
end
From my work the other night, I know that the CouchDB view will return an ingredient list of the form:
  before(:each) do
@ingredients = [{'butter' =>
[
['recipe-id-1', 'title 1'],
['recipe-id-2', 'title 2']
]
},
{'sugar' =>
[
['recipe-id-2', 'title 2']
]
}]
end
Given that, I expect to find a list of two ingredients:
  it "should have a list fo ingredients" do
render("/views/ingredients.haml")
response.should have_selector("p .ingredient", :count => 2)
end
I can get that to pass with:
= @ingredients.each do |ingredient|
%p
%span.ingredient
= ingredient.keys.first
Last up tonight, I would like to include the recipe titles in the Haml output:
  it "should have a list of recipes using the ingredients" do
render("/views/ingredients.haml")
response.should have_selector("p", :content => 'title 1, title 2')
end
I can get that passing with:
= @ingredients.each do |ingredient|
%p
%span.ingredient
= ingredient.keys.first
%span.recipes
= ingredient.values.first.map{|recipe| recipe[1]}.join(", ")
At this point, I am well on my way to completing the template. Hopefully I can finish it off tomorrow.

Friday, September 4, 2009

Always Check Boundary Conditions, You Dumb Ass

‹prev | My Chain | next›

A bit of less CSS work and my mini-calendar is functional and pretty:


(commit)

Sadly, a bit of smoke testing turns up a little problem:



Dang it! I missed a boundary condition in my Haml template:
#...
- week = 0
- while ((sunday0 + week*7).mon <= day1.mon)
#...
The value of sunday0 represents the very first day on the calendar. For January 2008, that Sunday was December 30:
cstrom@jaynestown:~/repos/eee-code$ cal 01 2008
January 2008
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Oops. For week zero, the month is 12, but day1.mon is 1. In other words, the while condition evaluates to false immediately.

Dumb ass. Always check boundary conditions.

To drive the boundary condition check, I write a quick Cucumber scenario:
   Scenario: Navigating boundary conditions

Given a "Test" meal enjoyed on 2008-01-23
And a "Test" meal enjoyed on 2007-12-15
When I visit the mini-calendar
Then I should see the calendar for January 2008
And there should be 1 links to meals
When I click on the link to the previous month
Then I should see the calendar for December 2007
And there should be 1 links to meals
Since I am re-using previously defined steps, this scenario should pass right away. Of course, I have that little bug in there:
  Scenario: Navigating boundary conditions
Given a "Test" meal enjoyed on 2008-01-23
And a "Test" meal enjoyed on 2007-12-15
When I visit the mini-calendar
Then I should see the calendar for January 2008
And there should be 1 links to meals
expected following output to contain a <td a/> tag:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head><link href="/stylesheets/style.css" rel="stylesheet" type="text/css"></head>
<html><body id="mini-calendar">
<h1>
<span class="previous">
<a href="/mini/2007/12"><</a>
</span>
January 2008
<span class="next">
>
</span>
</h1>
<table id="mini-calendar"><tr class="day-names">
<th>Su</th>
<th>M</th>
<th>Tu</th>
<th>W</th>
<th>Th</th>
<th>F</th>
<th>Sa</th>
</tr></table>
</body></html>
</html>
(Spec::Expectations::ExpectationNotMetError)
features/mini_calendar.feature:33:in `And there should be 1 links to meals'
When I click on the link to the previous month
Then I should see the calendar for December 2007
And there should be 1 links to meals

Failing Scenarios:
cucumber features/mini_calendar.feature:27 # Scenario: Navigating boundary conditions

1 scenario (1 failed)
8 steps (1 failed, 3 skipped, 4 passed)
0m0.593s
I could just as easily have probed this via an example. Through the use of a Cucumber scenario, I can easily verify my fix not only for the January side of the boundary, but also the December side. Besides, there is a difference between driving the fix (via examples) and verifying the fix (with Cucumber).

The RSpec example that will drive the desired behavior in the Haml template:
  context "January" do
before(:each) do
assigns[:month] = "2008-01"
end

it "should have weeks (probing boundary condition)" do
render("views/mini_calendar.haml")
response.should have_selector("td")
end
end
First, I check to see that this example does fail:
cstrom@jaynestown:~/repos/eee-code$ spec ./spec/views/mini_calendar.haml_spec.rb
..............F

1)
'mini_calendar.haml January should have weeks (probing boundary condition)' FAILED
expected following output to contain a <td/> tag:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head><link href="/stylesheets/style.css" rel="stylesheet" type="text/css"></head>
<html><body id="mini-calendar">
<h1>
<span class="previous">
<
</span>
January 2008
<span class="next">
<a href="/mini/2008/02">></a>
</span>
</h1>
<table id="mini-calendar"><tr class="day-names">
<th>Su</th>
<th>M</th>
<th>Tu</th>
<th>W</th>
<th>Th</th>
<th>F</th>
<th>Sa</th>
</tr></table>
</body></html>
</html>
./spec/views/mini_calendar.haml_spec.rb:107:

Finished in 0.255642 seconds

15 examples, 1 failure
To make this example pass (and hopefully the entire Cucumber scenario), I will update the while condition to compare the ISO 8601 string representation of the month rather than the month itself. This relies on the string "2007-12" being less than "2008-01". The updated while:
...
- week = 0
- while ((sunday0 + week*7).strftime("%Y-%m") <= day1.strftime("%Y-%m"))
...
That makes the example pass as well as the entire Cucumber scenario:
cstrom@jaynestown:~/repos/eee-code$ cucumber -s \
features/mini_calendar.feature:27
Sinatra::Test is deprecated; use Rack::Test instead.
Feature: Mini-calendar

As a curious web user
I want to see a calendar indicating the most recent meals and recipes
So that I can have a sense of how active the site is

Scenario: Navigating boundary conditions
Given a "Test" meal enjoyed on 2008-01-23
And a "Test" meal enjoyed on 2007-12-15
When I visit the mini-calendar
Then I should see the calendar for January 2008
And there should be 1 links to meals
When I click on the link to the previous month
Then I should see the calendar for December 2007
And there should be 1 links to meals

1 scenario (1 passed)
8 steps (8 passed)
0m0.621s
Smoke testing also verifies that the fix has worked:


(commit)

A quick deploy with Vlad:
cstrom@jaynestown:~/repos/eee-code$ rake vlad:stop_app 
cstrom@jaynestown:~/repos/eee-code$ rake vlad:update vlad:migrate vlad:start_app
And the new mini-calendar feature is now on the beta site:



I am a little chagrined that I missed the boundary condition in the first place. Still, it is good to have another feature complete. I will start on one of the two remaining features tomorrow.

Wednesday, September 2, 2009

Slow, Slow, Slow... Done!

‹prev | My Chain | next›

I begin today with 9 of 17 steps passing in my mini-calendar Cucumber scenario. Slightly more than half done and completing one scenario per day has made for frustrating progress of late. Hopefully today will prove more fruitful.

For reference, the legacy site displays the mini-calendar as:



The Cucumber scenario currently fails when trying to navigate between months on the calendar (clicking the less-than sign). So far, the calendar always displays the month with the most recent meal in it. Any expectation that an older month should display fails:
cstrom@jaynestown:~/repos/eee-code$ cucumber -is      features/mini_calendar.feature
Sinatra::Test is deprecated; use Rack::Test instead.
Feature: Mini-calendar

As a curious web user
I want to see a calendar indicating the most recent meals and recipes
So that I can have a sense of how active the site is

Scenario: Navigating through months
Given a "Test" meal enjoyed on 2009-08-23
And a "Test" meal enjoyed on 2009-08-15
And a "Test" meal enjoyed on 2009-08-01
And a "Test" meal enjoyed on 2009-06-23
When I visit the mini-calendar
Then I should see the calendar for August 2009
And there should be 3 links to meals
And there should not be a link to the next month
When I click on the link to the previous month
Then I should see the calendar for July 2009
expected following output to contain a <h1>July 2009</h1> tag:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>EEE Cooks</title>
<link href="/stylesheets/style.css" rel="stylesheet" type="text/css">
</head>
<html><body>
<div id="header">
<div id="eee-header-logo">
<a href="/">
<img alt="Home" src="/images/eee_corner.png"></a>
</div>
</div>
<h1>
<span class="previous">
<a href="/mini/2009/06"><</a>
</span>
August 2009
<span class="next">
>
</span>
</h1>
<table id="mini-calendar">
...
</body></html>
</html>
(Spec::Expectations::ExpectationNotMetError)
features/mini_calendar.feature:18:in `Then I should see the calendar for July 2009'
And there should be no links to meals
And there should be a link to the next month
When I click on the link to the previous month
Then I should see the calendar for June 2009
And there should be 1 links to meals
And there should be a link to the next month
And there should not be a link to the previous month

Failing Scenarios:
cucumber features/mini_calendar.feature:7 # Scenario: Navigating through months

1 scenario (1 failed)
17 steps (1 failed, 2 skipped, 5 undefined, 9 passed)
0m0.727s
The month with the last meal in it (the only month that the mini-calendar currently displays) is derived from the meals/count_by_month CouchDB view:
get %r{/mini/.*} do
url = "#{@@db}/_design/meals/_view/count_by_month?group=true"
data = RestClient.get url
@count_by_month = JSON.parse(data)['rows']
@month = @count_by_month.last['key']

url = "#{@@db}/_design/meals/_view/by_date_short?" +
"startkey=%22#{@month.sub(/\d\d$/, '')}00%22&" +
"endkey=%22#{@month.sub(/\d\d$/, '')}99%22"
data = RestClient.get url
@meals_by_date = JSON.parse(data)['rows'].inject({ }) do |memo, m|
memo[m['value']['date']] = m['value']['title']
memo
end

haml :mini_calendar
end
In turn, the mini_calendar Haml template uses @month to draw the correct month view. The RSpec example that drove the current behavior is:
    it "should display the month" do
get "/mini/"
last_response.
should have_selector("h1", :content => "August 2009")
end
What I want is, given a /mini/2009/07 URL (instead of /mini/) to display July of 2009 instead of the default month. In other words, I want:
    it "should display requested month" do
get "/mini/2009/07"
last_response.
should have_selector("h1", :content => "July 2009")
end
That example fails because "August 2009" always displays, but I can get it to pass by slurping the date string into a RegExp and judicious use of a ternary when calculating the current month:
get %r{/mini/(.*)} do |date_str|
url = "#{@@db}/_design/meals/_view/count_by_month?group=true"
data = RestClient.get url
@count_by_month = JSON.parse(data)['rows']
@month = date_str == '' ? @count_by_month.last['key'] : date_str

...
In addition to getting that example passing, I earn a passing Cucumber step as well:



Yay! One more step done... but wait! Those next two steps describe existing functionality (now that the proper month is showing). I can define them as:
Then /^there should be no links to meals$/ do
response.should_not have_selector("table a")
end

Then /^there should be a link to the next month$/ do
response.should have_selector("a", :content => ">")
end
Those Cucumber steps pass, as does the previous skipped, I-should-see-June step:



Wheee! I am making progress now. In fact, that next undefined step looks very similar to the already passing "there should be 3 links to meals" step. So I change:
Then /^there should be 3 links to meals$/ do
response.should have_selector("td a", :count => 3)
end
To:
Then /^there should be (\d) links to meals$/ do |count|
response.should have_selector("td a", :count => count.to_i)
end
That gets me down to the very last step (the previously skipped step passes). Again, the functionality has already been driven into the code, so I can verify it in Cucumber with:
Then /^there should not be a link to the previous month$/ do
response.should_not have_selector("a", :content => "<")
end
And, just like that, I have gone from extremely slow progress to done:



Often the last 20% is the hardest. In this case, as is often the case with Cucumber, the hard part got done first. I feel much better now than I did yesterday. Tomorrow I will get started with styling the mini-calendar. Then: deployment of the new feature to the beta site.

Tuesday, September 1, 2009

Links Between Mini-Months

‹prev | My Chain | next›

Yesterday, I was able to get my mini-calendar working. It displays the month with the most recent meal and links to other meals within that month. Up tonight are links to other months:



I already have all of the information that I need in the mini-calendar Sinatra action, so work begins with the RSpec specification for the mini-calendar Haml template. The main specification block assigns the month instance variable to a value of "2009-08":
  before(:each) do
assigns[:month] = "2009-08"
assigns[:meals_by_date] = {"2009-08-08" => "Meal Title"}
end
I will also need the count of meals per month:
  before(:each) do
assigns[:month] = "2009-08"
assigns[:meals_by_date] = {"2009-08-08" => "Meal Title"}
assigns[:count_by_month] = [{"key" => "2009-07", "value" => 3},
{"key" => "2009-08", "value" => 3}]

end
Since August is currently shown, there should be a link to July:
  it "should link to the previous month" do
render("views/mini_calendar.haml")
response.should have_selector("a",
:href => "/meals/2009/07",
:content => "<")
end
Happily, I already have a helper for that. This Haml code makes the example pass:
  .previous
=link_to_adjacent_view_date(@month, @count_by_month, :previous => true) { |d, v| %Q|<a href="/meals/#{d.gsub(/-/, '/')}">&lt;&</a>| }
That helper signature has not improved in prettiness since last I saw it. I can still grok it after a bit (given a current date and a CouchDB reduced list, find the previous entry on the list and generate the HTML in the block). I need to clean that up soon. For now, though, it passes.

Since my before block does not include anything after August in the count by month list, I do not expect that there should be a link to the next month:
  it "should not link to the next month" do
render("views/mini_calendar.haml")
response.should_not have_selector("a",
:content => ">")
end
That passes without any changes (because I have done nothing that would insert a ">" anywhere in the web page). It is something of a useless example of this point, but still good to have. I would like the next month indicator to be present, but not active:
  it "should the next month indicator should not be a link" do
render("views/mini_calendar.haml")
response.should have_selector(".next",
:content => ">")
end
Simplistically, I can get this passing with:
  %span.next
&gt;
That is not going to be helpful when there ought to be links, but I will drive that with a different context (one in which there is a next month) and a separate example:
  context "meals in next month, but not previous" do
before(:each) do
assigns[:count_by_month] = [{"key" => "2009-08", "value" => 3},
{"key" => "2009-09", "value" => 3}]
end
it "should link to the next month" do
render("views/mini_calendar.haml")
response.should have_selector("a",
:href => "/meals/2009/09",
:content => ">")
end
end
As expected that fails because the &gt; is just text, not a link:
cstrom@jaynestown:~/repos/eee-code$ spec ./spec/views/mini_calendar.haml_spec.rb
...........F

1)
'mini_calendar.haml meals in next month, but not previous should link to the next month' FAILED
expected following output to contain a <a href='/meals/2009/09'>></a> tag:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<h1>
<span class="previous">

</span>
August 2009
<span class="next">
>
</span>
</h1>
...
I can get that passing with this Haml:
  %span.next
= link_to_adjacent_view_date(@month, @count_by_month) { |d, v| %Q|<a href="/meals/#{d.gsub(/-/, '/')}">></a>| } || "&gt;"
That example passes, but the previous example expecting the non-link &gt; text is no longer passing. I resolve that with a simple OR operator:
  %span.next
= link_to_adjacent_view_date(@month, @count_by_month) { |d, v| %Q|<a href="/meals/#{d.gsub(/-/, '/')}">></a>| } || "&gt;"
After driving similar behavior for links to previous months, I am ready to move back out to my Cucumber scenario to mark the links to previous / next months scenario as complete:
Then /^there should not be a link to the next month$/ do
response.should_not have_selector("a", :content => ">")
end

When /^I click on the link to the previous month$/ do
click_link "<"
end
At this point, following the links have no effect—the more recent month with meals always displays. The rest of the scenario describes the actual navigation, which I will pick up tomorrow.

Monday, August 31, 2009

Another Mini Step in the Mini Calendar

‹prev | My Chain | next›

I continue working on the homepage mini-calendar tonight. Last night and tonight, I drive by example the following Haml template:
  - week = 0
- while ((sunday0 + week*7).mon <= day1.mon)
%tr{:class => "week#{week+1}"}
- (0..6).map{|d| sunday0 + d + week*7}.each do |date|
%td{:id => date.to_s}
= date.mday if date.mon == day1.mon
- week = week + 1
I cannot help thinking that I could have done this without the week accumulator, but this is what the examples drove me to:
cstrom@jaynestown:~/repos/eee-code$ spec ./spec/views/mini_calendar.haml_spec.rb -cfs

mini_calendar.haml
- should show a human readable month and year
- should show a human readable month and year for other months
- should not include previous month's dates
- should have the first of the month in the first week
- should have the last of the month
- should not include next month's dates
I will consider this the "get it done" phase. The "do it right" phase can wait for another day.

Next, I need to link to meals in this month. In RSpec speak:
describe "mini_calendar.haml" do
before(:each) do
assigns[:month] = "2009-08"
assigns[:meals_by_date] = {"2009-08-08" => "Meal Title"}
end

it "should link to meals this month" do
render("views/mini_calendar.haml")
response.should have_selector("td#2009-08-08 a",
:href => "/meals/2009/08/08",
:title => "Meal Title")
end

To make that example pass, I add another layer of conditionals, checking the @meals_by_date instance variable:
  - week = 0
- while ((sunday0 + week*7).mon <= day1.mon)
%tr{:class => "week#{week+1}"}
- (0..6).map{|d| sunday0 + d + week*7}.each do |date|
%td{:id => date.to_s}
- if date.mon == day1.mon
- if @meals_by_date.include?(date.to_s)
%a{:href => date.strftime("/meals/%Y/%m/%d"),
:title => @meals_by_date[date.to_s]}
= date.mday
- else
= date.mday

- week = week + 1
With that, I can mark one more step as complete. In my Cucumber scenario there should be 3 days in the month with meals:
Then /^there should be 3 links to meals$/ do
response.should have_selector("td a", :count => 3)
end
Running the Cucumber scenario, I do indeed have one more step done:



Tomorrow I need to add navigation between months. I think I may have missed an edge case here as well, so another Cucumber scenario is in order.

Sunday, August 30, 2009

Small Steps / Mini Calendar

‹prev | My Chain | next›

With half a brain, I was able to drive by example a start on the homepage mini-calendar. I left off with the mini-calendar showing a numeric date and little else. This was all done in the Sinatra action:
get %r{/mini/.*} do
url = "#{@@db}/_design/meals/_view/count_by_month?group=true\&limit=1\&descending=true"
data = RestClient.get url
@last_month = JSON.parse(data)['rows'].first['key']

"<h1>#{@last_month}</h1>"
end
Although not an MVC framework, I have done my view code separately in Haml templates. So first up today is to write some examples for the mini-calendar view. As can be seen from the mini action, there will be a @last_month (with a meal) instance variable, so my examples will all expect that to be set. In RSpec:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper' )

describe "mini_calendar.haml" do
before(:each) do
assigns[:last_month] = "2009-08"
end
end
The first example will describe the date heading:
  it "should show a human readable month and year" do
render("views/mini_calendar.haml")
response.should have_selector("h1", :content => "August 2009")
end
Running this example, of course, I find failure due to the lack of the template:
cstrom@jaynestown:~/repos/eee-code$ spec ./spec/views/mini_calendar.haml_spec.rb 
F

1)
Errno::ENOENT in 'mini_calendar.haml should show a human readable month and year'
No such file or directory - ./views/mini_calendar.haml
/home/cstrom/repos/eee-code/spec/spec_helper.rb:25:in `read'
/home/cstrom/repos/eee-code/spec/spec_helper.rb:25:in `render'
./spec/views/mini_calendar.haml_spec.rb:9:

Finished in 0.00705 seconds

1 example, 1 failure
Once again I find myself in the familiar, comfortable confines of the change-the-message or make-it-pass cycle. I can change the above message by creating the template. The new failure message becomes:
cstrom@jaynestown:~/repos/eee-code$ spec ./spec/views/mini_calendar.haml_spec.rb 
F

1)
'mini_calendar.haml should show a human readable month and year' FAILED
expected following output to contain a <h1>August 2009</h1> tag:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

./spec/views/mini_calendar.haml_spec.rb:10:

Finished in 0.007892 seconds

1 example, 1 failure
Finally, I can make the example pass by displaying the current month inside an <h1> tag:
%h1
= month_text @last_month
The reason for the change-the-message or make-it-pass cycle is to ensure that every step is built on validated assumptions from the previous step. There is nothing worse than spending 10 minutes trying to solve a problem only to realize that you are solving the wrong problem (like creating the template with the wrong name).

I do notice a problem with my naming convention. The Haml template will always show the month requested, not the "latest month". The current step in the current Cucumber scenario drove a default date—the last month with a meal. But as mentioned, this template is displaying the requested month. So I change the expected instance variable in the examples from @last_month to @month:
describe "mini_calendar.haml" do
before(:each) do
assigns[:month] = "2009-08"
end

it "should show a human readable month and year" do
render("views/mini_calendar.haml")
response.should have_selector("h1", :content => "August 2009")
end
end
Oddly enough, that example still passes:
cstrom@jaynestown:~/repos/eee-code$ spec ./spec/views/mini_calendar.haml_spec.rb
.

Finished in 0.008105 seconds

1 example, 0 failures
The reason for the non-failure has to do with the month_text helper method:
    def month_text(date_frag)
Date.parse("#{date_frag}-01").strftime("%B %Y")
end
Since the @last_month variable is not being set in the example, date_frag argument is now nil. This means that Date.parse is now trying to parse the string "-01". How can that return an actual date? Somehow it does:
>> Date.parse("-01").to_s
=> "2009-08-01"
This example will fail in two days (once the example month is different than the current month). For the time being, I will create another example to fail as expected:
  it "should show a human readable month and year for other months" do
assigns[:month] = "2009-01"
render("views/mini_calendar.haml")
response.should have_selector("h1", :content => "January 2009")
end
That example does fail:
cstrom@jaynestown:~/repos/eee-code$ spec ./spec/views/mini_calendar.haml_spec.rb 
.F

1)
'mini_calendar.haml should show a human readable month and year for other months' FAILED
expected following output to contain a <h1>January 2009</h1> tag:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><h1>
August 2009
</h1></body></html>
./spec/views/mini_calendar.haml_spec.rb:16:

Finished in 0.010549 seconds

2 examples, 1 failure
Making that example pass is a simple matter of using the new @month instance variable:
%h1
= month_text @month
This was a nice demonstration of the value in taking small steps in the change-the-message or make-it-pass cycle. I could have easily made the changes without the small steps. I might even have made the change without introducing a subtle defect. By taking small steps, I know that I have not introduced a subtle defect.

With that, I can work my way back out to the Cucumber scenario to mark the current step as complete:
Then /^I should see the calendar for (.+)$/ do |date|
response.should have_selector("h1", :content => date)
end
Cucumber had not suggested the RegExp for the date—rather I saw an opportunity for re-use coming very soon. And, indeed, in addition to one newly passing step, I have some blue ones as well:



I spend a little more time driving days in the mini-calendar. Tomorrow I ought to be able to link to meals from the calendar and mark off another step or two in my scenario.

Monday, June 29, 2009

Quick Start on RSS Feeds

‹prev | My Chain | next›

Moving on to the next Cucumber feature, I need to implement RSS feeds. First up is the RSS feed for the meals:



It is nice that, once a project has reached a certain point, one or two steps are already defined when starting on a new feature or scenario. The "Given" step of 20 yummy meals is already working, so I am able to get right down to business of accessing the RSS feed. Since I have yet to define that action in the Sinatra application, I am done with my outside, Cucumber work and am ready to dive into the inside, driven by RSpec work.

In the legacy Rails app (and the legacy baked-from-XML version before it), the RSS feed was named main.rss. To keep disruption to a minimum, I will keep that name, which means that I first drive RSS implementation with this example:
  describe "GET /main.rss" do
it "should respond OK" do
get "/main.rss"
last_response.should be_ok
end
end
Implementation of this simple example is predictably simple:
get '/main.rss' do
""
end
Before switching to a RSS builder library, I implement a simple string bare bones RSS feed. This is a simpler step than going straight for the RSS builder. Simpler, smaller steps make for fewer things that can go wrong moving to subsequent steps, making for a smoother overall development process.

The example that I use to drive the bare bones RSS feed is:
    it "should be the meals rss feed" do
get "/main.rss"
last_response.
should have_selector("channel title",
:content => "EEE Cooks: Meals")
end
And the bare bones RSS feed that implements this example is:
get '/main.rss' do
"<channel><title>EEE Cooks: Title</title></channel>"
end
With that example passing, I will give the built-in ruby library RSS:Maker a try for building the real RSS feed. I convert the bare bones string version to:
get '/main.rss' do
content_type "application/rss+xml"

rss = RSS::Maker.make("2.0") do |maker|
maker.channel.title = "EEE Cooks: Title"
end

rss.to_s
end
When I run the spec, however, I get this failure:
2)
RSS::NotSetError in 'eee GET /main.rss should be the meals rss feed'
required variables of maker.channel are not set: link, description
./eee.rb:40:in `GET /main.rss'
OK, I guess I can understand that those two attributes are needed, so I add them:
get '/main.rss' do
content_type "application/rss+xml"

rss = RSS::Maker.make("2.0") do |maker|
maker.channel.title = "EEE Cooks: Title"
maker.channel.link = "http://www.eeecooks.com/"
maker.channel.description = "Meals from a Family Cookbook"
end

rss.to_s
end
Which makes the spec pass again.

That is a good stopping point for today. Tomorrow I will build up the items in the RSS feed by pulling them from CouchDB.

Sunday, June 28, 2009

Feedback on Meals & Recipes

‹prev | My Chain | next›

I start today with a note about yesterday's work: when URL encoding in Sinatra, use Rack::Utils.escape. It works and it will encode in the same way that Rack::Test would expect things to be encoded. Maybe an obvious suggestion, but with the myriad of URL encoding options available in the Ruby world, it seemed one worth noting.

I used Rack::Utils.escape in the meal feedback link:
%div
%a{:href => "/feedback?url=#{Rack::Utils.escape(@url)}&subject=#{Rack::Utils.escape("[Meal] " + @meal['title'])}"} Send us feedback on this meal
Yesterday, I used the subject and url query parameters in that link to pre-populate the feedback form. Today, I need to ensure that the url parameter, when submitted by the feedback form to the "send us email" action does something. Specifically, it ought to include the URL in the email that we receive.

Unfortunately, because the email body is only one attribute to the Pony.mail call, I have to specify the entire body of the email message. I can use RSpec's hash_including so that I do not have to specify all of the Pony.mail attributes, but I still need the entire message body:
    it "should include the URL (if supplied) in the email" do
message = <<"_EOM"
From: from
Email: email

Message

URL: http://example.org/
_EOM

Pony.
should_receive(:mail).
with(hash_including(:body => message))

post "/email",
:name => "from",
:email => "email",
:subject => "Subject",
:message => "Message",
:url => "http://example.org/"
end
I get that and the previous non-URL example passing with this email action:
post '/email' do
message = <<"_EOM"
From: #{params[:name]}
Email: #{params[:email]}

#{params[:message]}
_EOM

message << "\nURL: #{params[:url]}\n" if params[:url]

Pony.mail(:to => "us _at_ eeecooks.com".gsub(/\s*_at_\s*/, '@'),
:subject => params[:subject],
:body => message)

haml :email
end
With that, I am ready to work my way back out to the Cucumber scenario to mark it as complete:



I implement the last step, that the form's subject should be pre-filled, with:
Then /^I should see a subject of "([^\"]*)"$/ do |subject|
response.should have_selector("input",
:value => subject)
end
And now, I have the entire meal feedback scenario complete:
cstrom@jaynestown:~/repos/eee-code$ cucumber features -n \
-s "Give feedback to the authors on a yummy meal"
Sinatra::Test is deprecated; use Rack::Test instead.
Feature: Site

So that I may explore many wonderful recipes and see the meals in which they were served
As someone interested in cooking
I want to be able to easily explore this awesome site

Scenario: Give feedback to the authors on a yummy meal
Given a "Yummy" meal enjoyed on 2009-06-27
When I view the "Yummy" meal
And I click "Send us feedback on this meal"
Then I should see a feedback form
And I should see a subject of "[Meal] Yummy"

1 scenario
5 passed steps
After driving-by-example a similar feedback link in the recipe.haml template, I can mark the recipe-feedback scenario as complete as well:
cstrom@jaynestown:~/repos/eee-code$ cucumber features -n \
> -s "Send compliments to the chef on a delicious recipe"
Sinatra::Test is deprecated; use Rack::Test instead.
Feature: Site

So that I may explore many wonderful recipes and see the meals in which they were served
As someone interested in cooking
I want to be able to easily explore this awesome site

Scenario: Send compliments to the chef on a delicious recipe
Given a recipe for Curried Shrimp
When I view the recipe
And I click "Send us feedback on this recipe"
Then I should see a feedback form
And I should see a subject of "[Recipe] Curried Shrimp"

1 scenario
5 passed steps
Not bad—two scenarios done in one night. Up next: RSS Feeds.

Wednesday, June 24, 2009

Feedback

‹prev | My Chain | next›

The next Cucumber scenario to implement is a somewhat simple feedback form. The very first incarnation of the site was static HTML baked from XML (even many of the search pages were baked). As such, we could not easily do in-page comments (pre-dated prototype.js and jQuery).

Even today, we still prefer the feedback form rather than on-page comments. It is amazing how rude some people can be when commenting on a family cookbook.

The scenario so far:
cstrom@jaynestown:~/repos/eee-code$ cucumber features -n \
-s "Give feedback to the authors of this fantastic site"
Sinatra::Test is deprecated; use Rack::Test instead.
Feature: Site

So that I may explore many wonderful recipes and see the meals in which they were served
As someone interested in cooking
I want to be able to easily explore this awesome site

Scenario: Give feedback to the authors of this fantastic site
Given 25 yummy meals
When I view the site's homepage
And I click "Send us comments"
Could not find link with text or title or id "Send us comments" (Webrat::NotFoundError)
features/site.feature:50:in `And I click "Send us comments"'
Then I should see a feedback form
When I fill out the form with effusive praise
And click the submit button
Then I should see a thank you note

1 scenario
1 failed step
4 undefined steps
2 passed steps
There is nothing in the way of behavior in the addition of a link to a feedback form. Still there is some semantic information in how this should be added to the homepage, so an example is in order. The feedback link should be included as part of an "About Us" section in the right-hand column of the homepage:
  it "should have a recipe search section" do
render("/views/index.haml")
response.should have_selector(".rhc h1",
:content => "About Us")
end
I implement this, including the link to the feedback form with the following Haml:
  .home-section
%h1 About Us
%p We are a young family living in the Baltimore area. One day we decided to put our recipe box online. This is our family cookbook
%p
%a{:href => "/feedback"} Send us comments
That gets the "Send us comments" step passing:



The next steps in the Cucumber scenario describe the feeback page, which does not yet exist. That means it is time to start working my way back into the code. First, the Sinatra application needs to respond to a feedback URL:
  describe "GET /feedback" do
it "should respond OK" do
get "/feedback"
last_response.should be_ok
end
end
Initially, I implement that with an empty string response (as the simplest thing that can work):
get '/feedback' do
""
end
I quickly replace that with a call to haml :feedback, which will need to be driven by example. The first example requires a name field for the feedback form:
  it "should include a field for the user's name" do
render("/views/feedback.haml")
response.should have_selector("label",
:content => "Name")
end
The first time I run the spec, I get an error:
1)
Errno::ENOENT in 'feedback.haml should include a field for the user's name'
No such file or directory - ./views/feedback.haml
/home/cstrom/repos/eee-code/spec/spec_helper.rb:25:in `read'
/home/cstrom/repos/eee-code/spec/spec_helper.rb:25:in `render'
./spec/views/feedback.haml_spec.rb:5
I change the message by creating a feedback.haml template:
cstrom@jaynestown:~/repos/eee-code$ touch views/feedback.haml
cstrom@jaynestown:~/repos/eee-code$ spec ./spec/views/feedback.haml_spec.rb
F

1)
'feedback.haml should include a field for the user's name' FAILED
expected following output to contain a tag:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

./spec/views/feedback.haml_spec.rb:6:

Finished in 0.008351 seconds
Finally, I am done changing the message, now I can make it pass:
%label
Name
%input{:type => "text", :name => "name"}
I follow a similar path to get email address, subject and message fields on this form.

I will call it a night at that point. I will pick up tomorrow implementing the form handler and moving closer to being complete with this scenario.

Before shutting down, I will mark my progress by defining the should-see-a-feedback-form step:
Then /^I should see a feedback form$/ do
response.should have_selector("h1", :content => "Feedback")
response.should have_selector("form")
end

Tuesday, June 23, 2009

Not Much of a Scenario

‹prev | My Chain | next›

With a little bit of cleanup behind, it's on to the next Cucumber scenario—exploring food categories from the homepage. The whole scenario:



Nice! Out of 12 steps in this scenario, 4 are already passing and 2 more are defined, but not yet reached.

The first undefined step in the scenario, clicking on the Italian category on the homepage, describes something missing on the homepage—category links. So, it is time for an RSpec example for the Haml template:
  it "should link to the listing of Italian recipes" do
render("/views/index.haml")
response.should have_selector("a",
:content => "Italian")
end
I implement that with a call to the categories helper, which links to the Italian category, as well as the other major categories on the site.

That is sufficient to implement the next step, "When I click the Italian category". Hey, that seems vaguely familiar. Have I already done something similar? In fact, I have:
When /^I click on the Italian category$/ do
click_link "Italian"
end
Hmm… I do not particularly care for the "on" that is currently in there. I think that it reads better without it, so I remove it from the text of an earlier scenario and from the step definition. While I am re-working that step anyway, I note that I will soon need to verify that the user can click the "Breakfast" category. To get the step passing for both categories, I use a Regexp matcher:
When /^I click the (\w+) category$/ do |category|
click_link category
end
With that step passing, I am up to the "Then I should see 20 recipes" step. Again, this seems familiar. Looking through the old recipe search feature step definitions, I find:
Then /^I should see (\d+) results$/ do |count|
response.should have_selector("table td a", :count => count.to_i)
end
That is just what I want! Changing the scenario text from "Then I should see 20 recipes" to "Then I should see 20 results", I find:
  Scenario: Exploring food categories (e.g. Italian) from the homepage # features/site.feature:31
Given 25 yummy meals # features/step_definitions/site.rb:1
And 50 Italian recipes # features/step_definitions/recipe_search.rb:119
And 10 Breakfast recipes # features/step_definitions/recipe_search.rb:119
When I view the site's homepage # features/step_definitions/site.rb:84
And I click the Italian category # features/step_definitions/site.rb:128
Then I should see 20 results # features/step_definitions/recipe_search.rb:241
expected following output to contain a <table td a/> tag:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head><title>EEE Cooks</title></head>
<html><body>
<div id="header">
<div id="eee-header-logo">
<a href="/">
<img alt="Home" src="/images/eee_corner.png"></a>
</div>
</div>
<ul id="eee-categories">
<li><a href="/recipes/search?q=category:italian">Italian</a></li>
<li><a href="/recipes/search?q=category:asian">Asian</a></li>
<li><a href="/recipes/search?q=category:latin">Latin</a></li>
<li><a href="/recipes/search?q=category:breakfast">Breakfast</a></li>
<li><a href="/recipes/search?q=category:chicken">Chicken</a></li>
<li><a href="/recipes/search?q=category:fish">Fish</a></li>
<li><a href="/recipes/search?q=category:meat">Meat</a></li>
<li><a href="/recipes/search?q=category:salad">Salad</a></li>
<li><a href="/recipes/search?q=category:vegetarian">Vegetarian</a></li>
<a>Recipes</a>
</ul>
<form action="/recipes/search" method="get">
<input maxlength="2048" name="query" size="31" type="text" value="category:italian"><input name="s" type="submit" value="Search">
</form>
<p class="no-results">
No results matched your search. Please refine your search
</p>
Aw nuts! And I was on such a roll…

Upon further inspection, I note that there were no matches on the Italian recipe category. The source of the trouble was the implementation of the "Given 50 Italian recipes" step. That step, as shown in the Cucumber output, was defined for the recipe search feature. It was defined without categories. The text after the number ("Italian") was used to build the recipe title, not to assign categories. Since that step made no use of the categories / tag_names, I am free to make use of it now:
Given /^(\d+) (.+) recipes$/ do |count, keyword|
date = Date.new(2009, 4, 22)

(1..count.to_i).each do |i|
permalink = "id-#{i}-#{keyword.gsub(/\W/, '-')}"

recipe = {
:title => "#{keyword} recipe #{i}",
:date => date,
:preparations => [
{ 'ingredient' => { 'name' => 'ingredient' } }
],
:tag_names => [keyword.downcase]

}

RestClient.put "#{@@db}/#{permalink}",
recipe.to_json,
:content_type => 'application/json'
end
end
After making similar adjustments for the next several steps, I am on the last step of this scenario—when I search for a category that only has 10 recipes (i.e. is less that the search page size), then I should see no more result pages. I define this step with the assumption that, in such a case, the "Next" link should be inactive:
Then /^I should see no more pages of results$/ do
response.should have_selector(".inactive", :content => "Next »")
end
And, just like that, I have another scenario complete:



There are still a few more scenarios in need of implementation, but I am getting very close to deploying.

Tuesday, June 16, 2009

Categorizing Meals

‹prev | My Chain | next›

The next couple of items in the navigation-from-the-homepage Cucumber involve clicking through to a meal:



The next undefined step is "When I click on the first meal". Hmm... I think I forgot to link to the meals from the homepage. Looking closer I find an example that superficially describes linking to meals, but actually only verifies that it includes the title text:
  it "should link to the meal titles" do
render("/views/index.haml")
response.should have_selector("h2", :content => "Bar")
end
I rename that example as "should include meal titles". Then I create the real example for linking to meals:
  it "should link to the the meal titles" do
render("/views/index.haml")
response.should have_selector("a",
:href => "/meals/2009/05/15",
:content => "Bar")
end
Once I get that passing by adding the appropriate %a Haml tag, it is time to move back to the Cucumber scenario. I can mark the next two steps as passing at this point. I can both click a meal link and verify that I am on the meal page:
When /^I click on the first meal$/ do
click_link "Meal 0"
end

Then /^I should see the meal page$/ do
response.should have_selector("h1",
:content => "Meal 0")
end
Those two steps pass, putting me half way through the exploration-from-the-homepage scenario:



The next "then" step states that "the Italian category should be highlighted". I already have something similar for the recipe page:
%ul#eee-categories
%li= recipe_category_link(@recipe, 'Italian')
%li= recipe_category_link(@recipe, 'Asian')
...
To determine if a meal is Italian, each of the recipes on the menu need to be checked. If any of them are Italian, then the meal will be considered Italian. So I'll need to load the recipes and I'll need to update the recipe_category_link to handle more than one recipe.

First up, loading a recipe from wiki text. For text similar to "[recipe:2009/06/16]", CouchDB should be queried and the results parsed:
describe "wiki_recipe" do
before(:each) do
@json = '{"_id":"2009-06-16-recipe","title":"Recipe for Foo"}'
end
it "should lookup a recipe from recipe wiki text" do
RestClient.
should_receive(:get).
with(/2009-06-16/).
and_return(@json)

wiki_recipe(" [recipe:2009/06/16]")
end
it "should return a recipe from recipe wiki text" do
RestClient.
stub!(:get).
and_return(@json)

wiki_recipe(" [recipe:2009/06/16]").
should == { "_id" => "2009-06-16-recipe",
"title" => "Recipe for Foo" }

end
it "should return nil for non-recipe wiki text" do
wiki_recipe("[rcip:2009/06/16]").should be_nil
end
end
I can make those three examples pass with:
    def wiki_recipe(text)
if text =~ /\[recipe:([-\/\w]+)/
permalink = $1.gsub(/\//, '-')
JSON.parse(RestClient.get("#{_db}/#{permalink}"))
end
end
When viewing a meal, I load all recipes into an instance variable in the Sinatra app:
  @recipes = @meal['menu'].map { |m| wiki_recipe(m) }.compact
With the Sinatra app using wiki_recipe to lookup recipes, I need to get recipe_category_link to use multiple recipes to determine whether or not to highlight category links. The example uses two "recipes", one with an "italian" category, which should highlight the link:
  it "should create an active link if any recipes include the category" do
recipes = [{ 'tag_names' => ['italian'] },
{ 'tag_names' => ['foo'] }]
recipe_category_link(recipes, 'Italian').
should have_selector("a", :class => "active")
end
I make that example pass (while keeping the existing, non-array examples passing) with:
    def recipe_category_link(recipe, category)
recipes = recipe.is_a?(Array) ? recipe : [recipe]
if recipes.any? { |r|
r['tag_names'] &&
r['tag_names'].include?(category.downcase)
}
%Q|<a class="active">#{category}</a>|
else
%Q|<a>#{category}</a>|
end
end
I then use the new recipe_category_link and the @recipes instance variable assigned in the Sinatra application to build category links in the meal Haml template:
%ul#eee-categories
%li= recipe_category_link(@recipes, 'Italian')
%li= recipe_category_link(@recipes, 'Asian')
%li= recipe_category_link(@recipes, 'Latin')
%li= recipe_category_link(@recipes, 'Breakfast')
%li= recipe_category_link(@recipes, 'Chicken')
%li= recipe_category_link(@recipes, 'Fish')
%li= recipe_category_link(@recipes, 'Meat')
%li= recipe_category_link(@recipes, 'Salad')
%li= recipe_category_link(@recipes, 'Vegetarian')
%li
%a Recipes
Finally, with that in place, I work back out to the Cucumber scenario. Implementing the Italian-category-should-be-highlighted step:
Then /^the Italian category should be highlighted$/ do
response.should have_selector("a",
:class => "active",
:content => "Italian")
end
And now, I am one step closer to being done with this scenario:


(commit)

Astute readers will note that the recipe_category_link omits the href attribute. It is not much of a link without that attribute. Fortunately, subsequent steps in this scenario cover this omission. Something for another day.

Sunday, June 14, 2009

Meal Photos and Menu Items

‹prev | My Chain | next›

Today, I continue work on the navigation-from-the-homepage Cucumber scenario. Yesterday, I was able to include meal summaries on the homepage. The next two steps in the scenario are additional "thens" (post-conditions) verifying that a meal thumbnail and menu items are also included on the homepage.

Nothing new needs to be added to the Sinatra application to include either of these pieces of information. This means that work today begins with the Haml specification to drive the new data presentation.

The example of how I'd like the thumbnail to display:
  it "should include a thumbnail image of the meal" do
render("/views/index.haml")
response.should have_selector("img",
:src => "/images/2009-05-15/image1.jpg",
:width => "200",
:height => "150")
end
I already have an image_link helper, so I can make this example pass with a simple call to that helper:
    = image_link meal, :width => 200, :height => 150
Next, I need two examples describing the presentation of each meal's menu items on the homepage. They should be wikified and comma separated:
  it "should include a comma separated list of menu items" do
assigns[:meals][0]["menu"] << "chips"
assigns[:meals][0]["menu"] << "salsa"
render("/views/index.haml")
response.should have_selector(".menu-items",
:content => "chips, salsa")
end

it "should wikify menu items" do
assigns[:meals][0]["menu"] << "_really_ hot salsa"
render("/views/index.haml")
response.should have_selector(".menu-items em",
:content => "really")
end
The entire index.haml template that implements this:
.meals
%h1 Meals
- @meals.each do |meal|
= image_link meal, :width => 200, :height => 150
%h2= meal["title"]
= wiki(meal["summary"])
.menu-items= wiki(meal["menu"].join(", "))
With that, I am done with my inside/code work for today. Working my was back out to the Cucumber scenario, I need to include an image attachment if I expect to include it in the homepage:
Given /^(\d+) yummy meals$/ do |count|
start_date = Date.new(2009, 6, 11)

@meal_ids = (0...count.to_i).inject([]) do |memo, i|
date = start_date - (i * 10)

meal = {
:title => "Meal #{i}",
:date => date.to_s,
:serves => 4,
:summary => "meal summary",
:description => "meal description",
:type => "Meal",
:menu => [],
:_attachments => { "meal#{i}.jpg" => {
:data => "R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAEBMgA7",
:content_type => "image/gif"}

}
}

RestClient.put "#{@@db}/#{date.to_s}",
meal.to_json,
:content_type => 'application/json'

memo + [date.to_s]
end
end
The content is the base64 encoded content of good old 1x1 spacer.gif. It does not matter much what the content is for the purposes of the Cucumber scenario—just that the filename ends with "jpg" (implementation detail of the image_link helper). With images attached to each meal, I can verify this Cucumber step with:
Then /^the prominently displayed meals should include a thumbnail image$/ do
response.should have_selector("img", :count => 10)
end
That's a good stopping point for tonight. Tomorrow, I will mark off the meals-should-include-recipe-titles step as complete. I already have enough code to implement that step, but have a kink or two that needs working out before I consider it really done.

Wednesday, June 10, 2009

RSpec Between Meals

‹prev | My Chain | next›

First up tonight, I need to link to more human readable text when navigating between meals. So I add the following RSpec example to drive this:
  it "should link to easily human readable previous meal" do
render("/views/meal.haml")
response.should have_selector("a", :content => "May 15, 2009")
end
I can make this example pass with some help from Date's strftime:
%div.navigation
‹
=link_to_adjacent_view_date(@meal['date'], @meals_by_date, :previous => true) { |d| Date.parse(d).strftime("%B %e, %Y") }
|
=link_to_adjacent_view_date(@meal['date'], @meals_by_date) { |d| d.strftime("%B %e, %Y") }
›
(my link_to_adjacent_view_date takes an optional block argument that produces the link text).

With that I have reached the refactor portion of the red-green-refactor cycle. I target these two examples for refactoring:
  it "should link to previous meal" do
render("/views/meal.haml")
response.should have_selector("a", :href => "/meals/2009/05/15")
end

it "should link to easily human readable previous meal" do
render("/views/meal.haml")
response.should have_selector("a", :content => "May 15, 2009")
end
I can combine those into a single, easier to read spec:
  it "should link to previous meal" do
render("/views/meal.haml")
response.should have_selector("a",
:href => "/meals/2009/05/15",
:content => "May 15, 2009")
end
So, is time to move back out to the Cucumber scenario? Not quite, the current failing step is trying to click on the meal name, not the date as I have just implemented.

The difficulty with this is that the link_to_adjacent_view_date helper was implemented to yield just the date for presentation. In this case, I need the title as well. That information is in the CouchDB view from last night, which has data that looks like:
{"total_rows":7,"offset":0,"rows":[
{"id":"2002-04-21","key":"2002/04/21","value":["2002-04-21","Sausage Vegetable Grits"]},
{"id":"2002-04-23","key":"2002/04/23","value":["2002-04-23","Black Bean Chili and Fried Grits"]},
{"id":"2002-07-06","key":"2002/07/06","value":["2002-07-06","Mac 'n' Cheese"]},
{"id":"2003-02-09","key":"2003/02/09","value":["2003-02-09","What To Do with Leftover Bubba's"]},
{"id":"2003-05-26","key":"2003/05/26","value":["2003-05-26","Biscuits and Gravy"]},
{"id":"2003-09-24","key":"2003/09/24","value":["2003-09-24","Almost French Onion Soup"]},
{"id":"2006-05-03","key":"2006/05/03","value":["2006-05-03","The Bestest Dinner Ever"]}
]}
The key is the date of meal, the value is a two element array of the id and title. So, yielding both key and value ought to allow me to retain the current date linking behavior (with some modifications), but also support the title linking behavior.

Before I implement this, I have to ask, do I really need the meal text? I already have navigation between meals working—the user can click on the date link. The user, eh? Thinking back to the feature that is driving this inside work, the user is described as "a person interested in exploring meals and how they drive certain recipes". I think such a user is much more likely to be engaged in exploration if the meal titles are shown. It is still worthwhile keeping the dates—if nothing else, they provide a clue to the user as to how the between meal links work (i.e. they are date ordered).

Phew! Confident that I am justified in adding this next bit of behavior, I will need to modify the example of the current behavior:
describe "link_to_adjacent_view_date" do
context "couchdb view by_month" do
before(:each) do
@count_by_month = [{"key" => "2009-04", "value" => 3},
{"key" => "2009-05", "value" => 3}]
end

it "should link to block text + date, if block is given" do
link_to_adjacent_view_date("2009-04", @count_by_month) do |date|
"foo #{date} bar"
end.
should have_selector("a",
:href => "/meals/2009/05",
:content => "foo 2009-05 bar")
end
end
end
That example reads, given the CouchDB view (@count_by_month), linking to a date adjacent to the supplied date, I should be able to incorporate the date into my own date string (here, surrounding the date with the words "foo" and "bar").

Now I need to support two arguments, instead of one, so the example is updated to read:
    it "should link to the CouchDB view's key and value, if block is given" do
link_to_adjacent_view_date("2009-04", @count_by_month) do |date, value|
"foo #{date} bar #{value} baz"
end.
should have_selector("a",
:href => "/meals/2009/05",
:content => "foo 2009-05 bar 3 baz")
end
Now, I expect the link_to_adjacent_view_date helper to yield with the CouchDB value, in addition to the date (key) that it had been yielding. That example verifies that the value ("3" from the context above) is usable as I expect it to be.

Running the spec fails now:
cstrom@jaynestown:~/repos/eee-code$ spec ./spec/eee_helpers_spec.rb 
...............................F..............

1)
'link_to_adjacent_view_date couchdb view by_month should link to the CouchDB view's key and value, if block is given' FAILED
expected following output to contain a <a href='/meals/2009/05'>foo 2009-05 bar 3 baz</a> tag:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><a href="/meals/2009/05">foo 2009-05 bar baz</a></body></html>
./spec/eee_helpers_spec.rb:241:

Finished in 0.044204 seconds

46 examples, 1 failure
I can make that pass by changing link_to_adjacent_view_date to yield the key and value to build the link text:
        link_text = block_given? ?
yield(next_result['key'], next_result['value']) :
next_result['key']
I have to update all instances of link_to_adjacent_view_date that use a block to expect two parameters (even if the second one is not used). With all specs passing, it is back to the meal spec to use the meal title in the link text:
  it "should link to previous meal title" do
render("/views/meal.haml")
response.should have_selector("a",
:href => "/meals/2009/05/15",
:content => "Foo")
end
(where "Foo" is the title a mock CouchDB view, defined in the spec setup)

To make that example pass, I change this line in the Haml template:
=link_to_adjacent_view_date(@meal['date'], @meals_by_date, :previous => true) { |d,v| Date.parse(d).strftime("%B %e, %Y") }
to read:
  =link_to_adjacent_view_date(@meal['date'], @meals_by_date, :previous => true) { |d,v| Date.parse(d).strftime("#{v[1]} (%B %e, %Y)") }
OK, now I am ready to work my way back out to the navigation-between-meals Cucumber scenario:



Yay! All passing. I am now assured that quick navigation between meals will work.
(commit)

I currently reside at the following Cucumber milemarker:
26 scenarios
1 skipped step
42 undefined steps
166 passed steps
Tomorrow, I will pick up with another scenario and try to get the number of undefined steps down under 40. I'm getting close.