【问题标题】:How can I "test" if response charset is utf-8 in a sinatra application using rspec?如果响应字符集在使用 rspec 的 sinatra 应用程序中是 utf-8,我如何“测试”?
【发布时间】:2012-02-04 21:38:45
【问题描述】:

我用

before do
  content_type "text/html", :charset => "utf-8"
end

在我的 sinatra 应用程序中。

如何检查这在我的 rspec 测试中是否有效?
我虽然应该是这样的:

it "should be utf-8 encoded" do
  get '/'
  last_response.body.encoding.should == 'utf-8'
end

但是encoding 不返回字符串。

【问题讨论】:

    标签: ruby encoding utf-8 rspec httpresponse


    【解决方案1】:

    您需要注意两种编码:

    • Content-Type 标头中声明响应的编码,
    • Ruby 将响应正文存储在 last_reponse.body 对象中的编码。

    一个好的 Rack 应用程序应该确保两者保持同步并且彼此一致,但是一些中间件组件或编码错误可能会使它们不匹配。所以你必须测试两者。

    此测试将确保正文字符串以“UTF-8”编码。

    it "should be UTF-8 encoded" do
        get '/'
        last_response.body.encoding.name.should == 'UTF-8'
    end
    

    这里我们正在测试如何将正文字符串编码为 Ruby 对象。

    (请注意,此代码仅适用于 Ruby 1.9.x。)

    相反,如果您想测试服务器是否为正文声明了 UTF-8 内容类型,您应该使用

    it "should have UTF-8 content type" do
        get '/'
        last_response.content_type.should =~ /UTF-8/
    end
    

    在第二个测试中,我们检查服务器是否声明它正在使用 UTF-8 编码,将 Content-Type 标头设置为包含 UTF-8 的内容。

    【讨论】:

      【解决方案2】:

      我是这样做的(任何其他解决方案将不胜感激):

      it "should be utf-8 encoded" do
        get '/'
        last_response.body.encoding.name.should == "UTF-8"
      end
      

      【讨论】:

        猜你喜欢
        • 2012-06-28
        • 1970-01-01
        • 2015-09-05
        • 2012-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-07
        • 1970-01-01
        相关资源
        最近更新 更多