簡體   English   中英

配置機架測試以間接啟動服務器

[英]Configuring rack-test to start the server indirectly

這是我的機架應用程序:

class MainAppLogic
    def initialize
        Rack::Server.start(:app =>Server, :server => "WEBrick", :Port => "8080")
    end
end

class Server
    def self.call(env)
        return [200, {},["Hello, World"]]
    end
end

實際運行時,它會按應有的方式運行,並向所有請求返回“ Hello World”。 我很難說服機架測試來使用它。 這是我的測試:

require "rspec"
require "rack/test"
require "app"

# Rspec config source: https://github.com/shiroyasha/sinatra_rspec    
RSpec.configure do |config|
    config.include Rack::Test::Methods
end

describe MainAppLogic do

    # App method source: https://github.com/shiroyasha/sinatra_rspec
    def app
        MainAppLogic.new
    end

    it "starts a server when initialized" do
        get "/", {}, "SERVER_PORT" => "8080"
        last_response.body.should be != nil
    end
end

當我對此進行測試時,它無法抱怨MainAppLogic不是機架服務器,特別是它沒有響應MainAppLogic.call 我如何讓它知道忽略MainAppLogic不是機架服務器,而只是向localhost:8080發出請求,因為那里的服務器已經啟動了?

第一件事:為什么要使用自定義類來運行應用程序? 您可以使用rackup工具,它是運行的應用程序機架的事實上的標准。 這里有一些更多的細節。

然后,您的應用程序代碼將變為:

class App
  def call(env)
    return [200, {}, ['Hello, World!']]
  end
end

並與config.ru

require_relative 'app'

run App.new

您可以通過在項目目錄中運行rackup來啟動應用程序。

至於錯誤,消息很清楚。 rack-test期望app方法的返回值將是rack app的實例(響應call方法的對象)。 看看rack-test內部發生了什么(作為提示,這很容易遵循—以給定的順序關注它們: lib/rack/test/methods.rb#L30 lib/rack/mock_session.rb#L7 lib/rack/test.rb#L244 lib/rack/mock_session.rb#L30 。注意Rack::MockSession的實例化,在處理請求時如何使用它(例如,當您在測試中調用get方法時),最后如何call應用上的方法已執行。

我希望現在很清楚為什么測試應該看起來像這樣(是的,執行測試時不需要運行服務器):

describe App do
  def app
    App.new
  end

  it "does a triple backflip" do
    get "/"
    expect(last_response.body).to eq("Hello, World")
  end
end

PS對不起, rack-test的鏈接形式,不能與我當前的得分相加超過2個:P

您的應用應為類名,例如,而不是:

def app
  MainAppLogic.new
end

你必須用

def app
  MainAppLogic
end

您無需指明執行get的端口,因為rack應用程序在測試的上下文中運行; 所以這應該是正確的方法:

it "starts a server when initialized" do
    get "/"
    last_response.body.should be != nil
end

另外,作為建議,建議使用新的expect格式而should格式,請參閱http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/

您的MainAppLogic應該是這樣的:

class MainAppLogic < Sinatra::Base
  get '/' do
    'Hello world'
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM