我最近在Thoughtbot blog post之后在我的Rails 4应用上启用了GZIP,并且我已根据this post的建议将use Rack::Deflater
添加到我的config.ru文件中。我的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
实施是否存在问题。
答案 0 :(得分:2)
正如@ andy-waite指出的那样,RSpec控制器规格并不知道中间件,但这就是为什么,因为RSpec 2.6我们有request specs。
根据文档要求规范:
旨在通过完整堆栈驱动行为
因此,使用RSpec&gt; 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
答案 1 :(得分:0)
RSpec控制器规范包含在Rails功能测试中,这些测试不了解中间件:
Making Rails tests aware of Rack middleware outside Rails's internal chain