2013-06-28 29 views

回答

2

我相信你的意思測試是否正在改變ENV ...

中間件雲一樣的東西:

class Foo 
    def initialize(app) 
    @app = app 
    end 

    def call(env) 
    # do stuff with env ... 
    status, headers, response = @app.call(env) 

    # do stuff with status, headers and response 
    [status, headers, response] 
    end 
end 

你可以用一個假的應用程序(或拉姆達初始化,對於物質),這樣做一些測試後返回虛擬迴應:

class FooTester 
    attr_accessor :env 

    def call(env) 
    # check that env == @env and whatever else you need here 
    [200, {}, ''] 
    end 
end 
+0

是的,我正在改變env。你能解釋FooTester的工作原理嗎?它如何稱爲Foo? –

+1

@BSeven:'tester = FooTester.new; tester.env = env; foo = Foo.new(測試人員); foo.call(env);' –

2

@丹尼斯的回答會的工作,但我個人更喜歡另一種,是把中間件一個裸機應用程序(無論是Sinatra還是其他),只是通過請求作爲響應並測試它。這是大多數Rack中間件的設計方式。那並且單元測試了中間件的內部。

例如,它就是我done here with a fork of Rack Clicky


編輯:分別測試中間件從主應用程序。

require 'lib/rack/mymiddelware.rb' 
require 'sinatra/base' 

describe "My Middleware" do 
    let(:app) { 
    Sinatra.new do 
     use MyMiddleware 
     get('/') { request.env.inspect } 
    end 
    } 
    let(:expected) { "Something you expect" } 
    before do 
    get "/" 
    end 
    subject { last_response.body } 
    it { should == expected } 
end 
+0

那麼如何將中間件包含在裸機架應用程序和使用它的應用程序中? –

+1

@BSeven使用匿名Sinatra類。我在答案中給出了一個例子。 – iain

相關問題