Testing sinatra helpers with rspec

Lately I built a simple Sinatra based demo application (YaSApp) and tried to test some methods within a helpers block

helpers do
  def human_date(datetime)
    datetime.strftime('%-d. %B %Y, %H:%M Uhr')
  end
end

But Rspec keept me sending NoMethod Errors:

NoMethodError:
  undefined method `human_date' for #<Sinatra::Application ...

Than I learned in the context of the Padrino framework, that this is a “special” Sinatra feature - so called “shorthand helpers”. Because above statement is shorthand for:

helpers = Module.new do
  def human_date(...
  end
end

Which is kind of a anonymous module and that way hard to reference or test!

The solution is to make a explicit module and propagate it to the application like this:

module AppHelpers
  def human_date(datetime)
    datetime.strftime('%-d. %B %Y, %H:%M Uhr')
  end
end

Sinatra::Application.helpers AppHelpers

and then it is testable in RSpec:

describe "AppHelpers" do
  subject do
    Class.new { include AppHelpers }
  end

  describe "#human" do
    it "formats date and time readable" do
      t = Time.new(2014,02,06,14,18,33)
      expect(subject.new.human_date t).to eq '6. February 2014, 14:18 Uhr'
    end
  end
end

Hope thats helpful for one or the other?

NO COMMENT BOX
Right, not here. But it doesn’t mean I’m not interested in your feedback. I just prefer to use more busy services ;-) where a wider discussion could incur. So tweet me @netzfisch or if you find an error, fork my blog, correct the post and send me a pull request via GitHub. Thanks for your efforts.
CHEAT SHEETS
ELSEWHERE