如何訪問應用程序實例,以便測試foobar()方法?如何在Sinatra應用程序中測試方法?
class App < Sinatra::Base
get '/' do
return foobar
end
def foobar
"hello world"
end
end
如何訪問應用程序實例,以便測試foobar()方法?如何在Sinatra應用程序中測試方法?
class App < Sinatra::Base
get '/' do
return foobar
end
def foobar
"hello world"
end
end
不要緊,你考什麼 - 它是如何:) =>http://www.sinatrarb.com/testing.html
這是一個遲到的答覆,但我試圖找到一種靈活的方式來做到這一點。
我在Sinatra的源代碼(1.4.5)中發現,使用new!
創建應用程序實例可以直接測試應用程序的方法。從Test :: Unit和Shoulda進行測試設置。
class AppTest < Test::Unit::TestCase
setup do
@app = App.new! # here is the point.
end
should 'say hello to the world' do
assert_equal "hello world", @app.foobar # or @app.send(:foobar) for private methods.
end
end
有後果。使用new!
不會創建通常變成entry point to the middleware pipeline and the app in normal settings的Sinatra::Wrapper
。因此,new!
方法只有在測試方法真的是「助手」時才能工作,這些「助手」不依賴於中間件功能(例如SSL)。
或者,post on Rspec提出了另一種解決方案。我過去使用過類似的東西,但它需要更多的工作,但並不總是最好的選擇。它有提供更廣泛的代碼測試覆蓋範圍的優勢。如果我們正在進行「單元」測試,那麼應用程序與new!
的隔離聽起來不錯。
關於@ three的評論注意:一個非平凡的應用程序應該將API方法(通常在應用程序中)與所有幫助器等分開。幫助器以單獨文件結尾更清晰,更容易維護並更容易測試。但我絕對理解應用的第一版本會包含一些幫助者的情況,並意識到重構將是必要的。即便如此,進行測試也會對軟件本身和未來的重構帶來更多的信心。
你爲什麼要在sinatra方法?使用視圖來返回內容。或者使用隨處可用的幫手。但是你通常不會在Sinatra測試方法。 – three
但是如果我有一個複雜的方法在我的get塊中使用,並且想單獨測試它呢? – Lilly
你可以創建一個課程並在那裏測試。 – three