Ove*_*ryd 14
我通过将辅助方法放在自己的模块中来单独测试我的sinatra助手.由于我的sinatra应用程序比通常的hello world示例稍微大一点,我需要将它分成更小的部分.普通助手的模块很适合我的用例.
如果你编写一个快速演示,并在helpers { ... }块中定义你的助手方法,我认为测试它是绝对必要的.生产中的任何sinatra应用程序可能需要更多的模块化.
# 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
Run Code Online (Sandbox Code Playgroud)
其实你不需要这样做:
helpers do
include FooBar
end
Run Code Online (Sandbox Code Playgroud)
既然你可以打电话
helpers FooBar
Run Code Online (Sandbox Code Playgroud)
该helpers方法采用混合模块列表和一个可选的块,该块在以下版本中进行了类评估:https://github.com/sinatra/sinatra/blob/75d74a413a36ca2b29beb3723826f48b8f227ea4/lib/sinatra/base.rb#L920- L923