Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test helpers blocks in Sinatra, using Rspec?

I'm writing a sinatra app and testing it with rspec and rack/test (as described on sinatrarb.com).
It's been great so far, until I moved some rather procedural code from my domain objects to sinatra helpers.

Since then, I've been trying to figure out how to test these in isolation ?

like image 213
julien Avatar asked May 21 '10 00:05

julien


3 Answers

I test my sinatra helpers in isolation by putting the helper methods within its own module. Since my sinatra application is a little bit bigger than the usual hello world example, I need to split it up into smaller parts. A module for the common helpers suits my use case well.

If you write a quick demo, and you define your helper methods within the helpers { ... } block, I don't think testing it is absolutely necessary. Any sinatra app in production, may require more modularity anyways.

# in helpers.rb
module Helpers
  def safe_json(string)
    string.to_s.gsub(/[&><']/) { |special| {'&' => '\u0026', '>' => '\u003E', '<' => '\u003C', "'" => '\u0027'}[special] }
  end
end

# in app.rb
helpers do
  include Helpers
end

# in spec/helpers_spec.rb
class TestHelper
  include Helpers
end

describe 'Sinatra helpers' do
  let(:helpers) { TestHelper.new }

  it "should escape json to inject it as a html attribute"
    helpers.safe_json("&><'").should eql('\u0026\u003E\u003C\u0027')
  end
end
like image 91
Overbryd Avatar answered Nov 09 '22 11:11

Overbryd


Actually you don't need to do:

helpers do
  include FooBar
end

Since you can just call

helpers FooBar

The helpers method takes a list of modules to mix-in and an optional block which is class-eval'd in: https://github.com/sinatra/sinatra/blob/75d74a413a36ca2b29beb3723826f48b8f227ea4/lib/sinatra/base.rb#L920-L923

like image 23
Nicolás Sanguinetti Avatar answered Nov 09 '22 13:11

Nicolás Sanguinetti


maybe this can help you some way http://japhr.blogspot.com/2009/03/sinatra-innards-deletgator.html

like image 2
zed_0xff Avatar answered Nov 09 '22 11:11

zed_0xff