いくつかの外部サービスを呼び出すSinatraアプリを書いています。私は明らかに私のテストが実際のサービスを呼び出さないようにしたいので、今私がこれを持っていると仮定します
class MyApp < Sinatra::Base
get '/my_method' do
@result = ExternalServiceHandler.new.do_request
haml :my_view
end
end
そして私のテストでは
describe "my app" do
include Rack::Test::Methods
def app() MyApp end
it "should show OK if call to external service returned OK" do
@external_service_handler = MiniTest::Mock.new
@external_service_handler.expect :do_request, "OK"
#Do the injection
get '/my_method'
response.html.must_include "OK"
end
it "should show KO if call to external service returned KO" do
@external_service_handler = MiniTest::Mock.new
@external_service_handler.expect :do_request, "KO"
#Do the injection
get '/my_method'
response.html.must_include "KO"
end
end
これを注入する方法は2つ考えられます。インスタンスメソッドを呼び出すか、コンストラクターを介して依存関係を渡すことができます。とにかく、ラックは現在のアプリケーションインスタンスへのアクセスを提供していないように見えるので、これは不可能だと思います。
このためのクラスメソッドを宣言することはできますが、可能であればインスタンスを使用することをお勧めします。それぞれの場合に異なるインジェクションを行う可能性を維持し、状態をロールバックするのを忘れた場合に他のテストに害を及ぼす可能性のあるグローバル状態を回避するため。
これを達成する方法はありますか?
前もって感謝します。