Ruby-on-rails 如何使用 Capybara + Selenium 测试响应代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7908907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:15:32  来源:igfitidea点击:

How to test the response code with Capybara + Selenium

ruby-on-railsseleniumrspeccapybara

提问by deb

I have the following spec:

我有以下规格:

it "deletes post", :js => true do 
...
...
page.status_code.should = '404'

end 

The page.status_codeline is giving me this error:

page.status_code行给了我这个错误:

Capybara::NotSupportedByDriverError

How do I check the page's status code?

如何查看页面的状态码?

采纳答案by eugen

status_codeis not currently supported by the Selenium driver. You will need to write a different test to check the response status code.

status_codeSelenium 驱动程序当前不支持。您将需要编写不同的测试来检查响应状态代码。

回答by Apie

As an aside. This line

作为旁白。这条线

page.status_code.should = '404'

Should be

应该

page.status_code.should == 404

This worked for me with capybara-webkit.

这对我使用 capybara-webkit 有用。

回答by Leonid Shevtsov

Either switch to another driver (like rack-test) for that test, or test that the displayed page is the 404 page (should have content 'Not Found' in h1).

要么切换到另一个驱动程序(如rack-test)进行该测试,要么测试显示的页面是 404 页面(在 h1 中应该有内容“未找到”)。

As @eugen said, Selenium doesn't support status codes.

正如@eugen 所说,Selenium 不支持状态代码。

回答by Oxyless

Selenium web driver doest not implement status_code and there is no direct way to test response_code with selenium (developer's choice).

Selenium Web 驱动程序不实现 status_code 并且没有直接的方法用 selenium 测试 response_code(开发人员的选择)。

To test it I added in my layout/application.html.erb:

为了测试它,我在 layout/application.html.erb 中添加了:

<html code="<%= response.try(:code) if defined?(response) %>">[...]</html>

And then in my test:

然后在我的测试中:

def no_error?
  response_code = page.first('html')[:code]
  assert (response_code == '200'), "Response code should be 200 : got #{response_code}"
end

回答by Ajay

Try it out

试试看

expect(page).to have_http_status(200)

回答by G. I. Joe

Use js to make a request and get status as below:

使用 js 发出请求并获取如下状态:

js_script = <<JSS
xhr = new XMLHttpRequest();
xhr.open('GET', '#{src}', true);
xhr.send();
JSS
actual.execute_script(js_script)
status = actual.evaluate_script('xhr.status') # get js variable value

Check https://gist.github.com/yovasx2/1c767114f2e003474a546c89ab4f90dbfor more details

检查https://gist.github.com/yovasx2/1c767114f2e003474a546c89ab4f90db了解更多详情