2015-05-28 27 views
4

我最近在這個Thoughtbot blog post之後在我的Rails 4應用上啓用了GZIP,並且我還向012.ru建議的我的config.ru文件添加了use Rack::Deflater。我的Rails應用似乎在提供壓縮內容,但是當我使用RSpec進行測試時,測試失敗,因爲response.headers['Content-Encoding']爲零。針對GZIPed響應的Rspec測試

這裏是我的application.rb中:

module MyApp 
    class Application < Rails::Application 
    # Turn on GZIP compression 
    config.middleware.use Rack::Deflater 
    end 
end 

這裏是我的規格:

require 'rails_helper' 

describe GeneralController, type: :controller, focus: true do 
    it "a visitor has a browser that supports compression" do 
     ['deflate', 'gzip', 'deflate,gzip', 'gzip,deflate'].each do |compression_method| 
      get 'about', {}, {'HTTP_ACCEPT_ENCODING' => compression_method } 
      binding.pry 
      expect(response.headers['Content-Encoding']).to be 
     end 
    end 

    it "a visitor's browser does not support compression" do 
     get 'about' 
     expect(response.headers['Content-Encoding']).to_not be 
    end 
end 

當我運行curl --head -H "Accept-Encoding: gzip" http://localhost:3000/我得到以下的輸出:

HTTP/1.1 200 OK 
X-Frame-Options: SAMEORIGIN 
X-Xss-Protection: 1; mode=block 
X-Content-Type-Options: nosniff 
X-Ua-Compatible: chrome=1 
Content-Type: text/html; charset=utf-8 
Vary: Accept-Encoding 
Content-Encoding: gzip 
Etag: "f7e364f21dbb81b9580cd39e308a7c15" 
Cache-Control: max-age=0, private, must-revalidate 
X-Request-Id: 3f018f27-40ab-4a87-a836-67fdd6bd5b6e 
X-Runtime: 0.067748 
Server: WEBrick/1.3.1 (Ruby/2.0.0/2014-02-24) 

當我加載該網站,看看檢查員的網絡選項卡我可以看到,響應大小比以前小,但我的測試仍然失敗。我不確定我是否在測試中錯過了一步,或者如果我的實施Rack::Deflater存在問題。

回答

2

正如@安迪 - 懷特指出,RSpec的控制器的規格都沒有意識到中間件,但是這就是爲什麼,自RSpec 2.6起,我們有request specs

請求規格是,根據文檔:

旨在通過完整的堆棧開車行爲

因此,使用的RSpec> 2.6的要求規範,代碼應該是這樣的:

require 'rails_helper' 

describe GeneralController, type: :request, focus: true do 
    it "a visitor has a browser that supports compression" do 
    ['deflate', 'gzip', 'deflate,gzip', 'gzip,deflate'].each do |compression_method| 
     get 'about', {}, {'HTTP_ACCEPT_ENCODING' => compression_method } 
     binding.pry 
     expect(response.headers['Content-Encoding']).to be 
    end 
    end 

    it "a visitor's browser does not support compression" do 
    get 'about' 
    expect(response.headers['Content-Encoding']).to_not be 
    end 
end