如何使用Rspec在Sinatra中测试助手块?

jul*_*ien 14 ruby testing rack rspec sinatra

我正在编写一个sinatra应用程序并使用rspec和rack/test进行测试(如sinatrarb.com所述).
到目前为止,它一直很棒,直到我将一些相当程序化的代码从我的域对象移动到sinatra助手.

从那时起,我一直在试图弄清楚如何隔离测试这些?

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)


Nic*_*tti 6

其实你不需要这样做:

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