我怎样才能“测试”如果使用 rspec 的 sinatra 应用程序中的响应字符集是 utf-8?

发布于 2025-01-02 16:27:46 字数 351 浏览 0 评论 0原文

使用

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 不会返回字符串。

I use

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

in my sinatra app.

How can I check if this works in my rspec tests?
I though it should be something like:

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

But encoding does not return a string.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

囍笑 2025-01-09 16:27:47

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

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

I did it like this (any other solution would be much appreciated):

it "should be utf-8 encoded" do
  get '/'
  last_response.body.encoding.name.should == "UTF-8"
end
最终幸福 2025-01-09 16:27:46

您需要注意两种编码:

  • 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 的内容。

You have two encoding to take care:

  • the encoding of the response declared in the Content-Type header,
  • the encoding in which Ruby has stored the response body inside the last_reponse.body object.

A good Rack application should make sure that the two are kept in sync and are coherent with each other, but some middleware component or coding error could make them mismatch them. So you have to test both.

This test will make sure that the body string is encoded in 'UTF-8'.

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

Here we are testing how the body string is encoded as Ruby object.

(Please beware that code this will work only on Ruby 1.9.x.)

Instead, if you want to test whether the server has declared an UTF-8 content type for the body, you should use

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

In this second test we check whether the server declared that it is using the UTF-8 encoding setting the Content-Type header to something that contains UTF-8.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文