Rspec测试针对GZIP压缩响应

4
我最近在我的Rails 4应用中启用了GZIP,按照Thoughtbot博客文章的指南进行操作。同时,我也像这篇文章所建议的那样,在我的config.ru文件中添加了use Rack::Deflater。我的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实现存在问题。
2个回答

2
如@andy-waite所指出的那样,RSpec控制器规范不知道中间件,但这就是为什么自RSpec 2.6以来我们有了request specs
根据文档,请求规范(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

0

我将Agustin发布的代码插入到我的rails_helper.rb文件中,但这并没有解决我的问题。 - Daniel Bonnell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接