ruby-on-rails – 针对GZIPed响应的Rspec测试

我最近在这个
Thoughtbot blog post之后在我的Rails 4应用程序上启用了GZIP,我还添加了使用Rack :: Deflater到我的config.ru文件,如
this post所示.我的Rails应用程序似乎提供压缩内容,但当我使用它测试时RSpec测试失败,因为response.headers [‘Content-Encoding’]为零.

这是我的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的实现是否存在问题.

最佳答案 正如@ andy-waite指出的那样,RSpec控制器规格并不知道中间件,但这就是为什么,因为RSpec 2.6我们有
request specs.

根据文档,请求规格是:

designed to drive behavior through the full stack

因此,使用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
点赞