Tuesday, March 31, 2009

Accessing Sinatra Helper Methods in View Specs

‹prev | My Chain | next›

I left off last night pondering how to make Sinatra helpers available to Haml view specs. I tried digging into how helpers works in Sinatra, but was unable to discern a way to put any of it to use.

My ultimate solution is to break out my helper methods into a file named helpers.rb:
module Eee
module Helpers
def hours(minutes)
h = minutes.to_i / 60
m = minutes.to_i % 60
h > 0 ? "#{h} hours" : "#{m} minutes"
Requiring that file and then mixing it in inside the Sinatra helpers block gets me back to where I was last night:
require 'helpers'

helpers do
include Eee::Helpers
In order to make the helper methods available to my view specs, I configure Spec::Runner to include the helper module:
Spec::Runner.configure do |config|
config.include Webrat::Matchers, :type => :views
config.include Eee::Helpers
Finally, I change the default scope of the Haml rendering from a vanilla Object.new to self:
def render(template_path)
template = File.read("./#{template_path.sub(/^\//, '')}")
engine = Haml::Engine.new(template)
@response = engine.render(self, assigns_for_template)
Binding the render call to self (instances of Test::Unit sub-classes) gives the Haml engine an object that defines the helper methods (because they were included in the configuration block).

With those changes, I have all of my views specs passing, including displaying 5 hours instead of 300 minutes:
cstrom@jaynestown:~/repos/eee-code$ ruby ./spec/views/recipe.haml_spec.rb -cfs 

- should display the recipe's title

recipe.haml a recipe with no ingredient preparations
- should not render an ingredient preparations

recipe.haml a recipe with 1 egg
- should render ingredient names
- should render ingredient quantities
- should not render a brand

recipe.haml a recipe with 1 cup of all-purpose, unbleached flour
- should include the measurement unit
- should include the specific kind of ingredient
- should read conversationally, with the ingredient kind before the name

recipe.haml a recipe with 1 12 ounce bag of Nestle Tollhouse chocolate chips
- should include the ingredient brand
- should note the brand parenthetically after the name

recipe.haml a recipe with an active and inactive preparation time
- should include preparation time
- should include inactive time

recipe.haml a recipe with no inactive preparation time
- should not include inactive time

recipe.haml a recipe with 300 minutes of inactive time
- should display 5 hours of Inactive Time

Finished in 0.063692 seconds

14 examples, 0 failures

I may want to simply stub my helper method calls inside my view specs and test my helper methods independently of my views. Something to decide another day.

No comments:

Post a Comment