11

我尝试使用几种变体来检查 Capybara 的 200 Ok HTTP 响应,但它们都不起作用:

response.should be_success
page.status.should be(200)
page.response.status.should == 200

还有一个吗?

4

5 回答 5

14

I found it:

page.status_code.should be 200

And it's work fine!!!

于 2013-02-03T11:16:15.583 回答
10

由于当前的 RSpec 版本发出弃用警告,我建议将您的解决方案更改为:

expect(page.status_code).to be(200)

这个对我有用。

PS 弃用警告如下:

弃用:不推荐使用shouldfrom rspec-expectations 的旧:should 语法而不显式启用该语法。改用新:expect语法或显式启用:should

于 2014-11-21T16:10:22.007 回答
3

两个答案和提问者都没有说他们使用的是哪个驱动程序。它是一个重要的信息,这使得差异。只是为了提供完整的信息,这不适用于 selenium webdriver,尽管它确实适用于 poltergeist 和 capybara-webkit驱动程序

于 2015-01-14T13:41:37.907 回答
0

作为一种替代方式,您可以使用 Ruby 的 Http 客户端 API 来检查响应代码或类型

单程 :

response = Net::HTTP.get_response(URI.parse(current_url))

expect(response.kind_of? Net::HTTPSuccess).to be_truthy

第二种方式:

response = Net::HTTP.get_response(URI.parse(current_url))

expect(response.code.to_i.eql?(200)).to be_truthy #response.code returns the code as a string

PS:您不需要下载任何外部 gem,因为它带有 Ruby 库

于 2019-08-26T02:05:32.813 回答
0

Selenium 令人讨厌地不提供任何标头或 HTTP 状态数据,所以我编写了这个中间件来注入一个 HTML 注释,其中包含与 Capybara 一起使用的 HTTP 状态代码。

module Vydia
  module Middleware
    class InjectHeadersForSelenium

      def initialize(app)
        @app = app
      end

      def call(env)
        @status, @headers, @response = @app.call(env)

        if @headers["Content-Type"] && @headers["Content-Type"].include?("text/html")
          @prepend = "<!-- X-Status-Code=#{@status} -->\n"
          @headers = @headers.merge(
            "Content-Length" => (@headers["Content-Length"].to_i + @prepend.size).to_s
          )
        end

        [@status, @headers, self]
      end

      def each(&block)
        if @prepend
          yield(@prepend)
          @prepend = nil
        end

        @response.each(&block)
      end

    end
  end
end

在测试中,您可以像这样获得状态代码:

def get_http_status
  begin
    page.driver.status_code
  rescue Capybara::NotSupportedByDriverError
    matches = /<!-- X-Status-Code=(\d{3}) -->/.match(page.body)
    matches && matches[1] && matches[1].to_i
  end
end

get_http_status
于 2017-11-21T17:00:51.090 回答