200 HTTP response with Capybara

I am trying to use several options to test a 200 Ok HTTP response with Capybara, but none of them work:

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

Is there another one?

+10
capybara
source share
5 answers

I found him:

 page.status_code.should be 200 

And it works great !!!

+13
source

Since the current version of RSpec gives an obsolescence warning, I would suggest changing your solution to:

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

This works for me.

PS The failure warning is as follows:

DEPRECATION: use of should from rspec-expectations' old :should syntax without explicit inclusion of syntax is deprecated. Use the new :expect syntax or explicitly include :should .

+8
source

both answers, and the questioner did not say which driver they use. Its important information that makes a difference. To provide complete information, this one does not work with selenium webdriver , although it works with poltergeist and capybara-webkit drivers

+3
source

Selenium annoyingly does not provide any header or HTTP status data, so I wrote this middleware to insert an HTML comment containing an HTTP status code for use with Capybara.

 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 

In tests, you can get the status code as follows:

 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 
0
source

Alternatively, you can use the Ruby Http client API to check the response code or enter

One way:

 response = Net::HTTP.get_response(URI.parse(current_url)) expect(response.kind_of? Net::HTTPSuccess).to be_truthy 

The second way:

 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: You do not need to download any external gems, as they come with the Ruby library

0
source

All Articles