如何使用 Capybara + Selenium 测试响应码

问题描述 投票:0回答:7

我有以下规格:

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

end 

page.status_code
行给我这个错误:

Capybara::NotSupportedByDriverError

如何查看页面的状态码?

ruby-on-rails selenium rspec capybara
7个回答
47
投票

顺便说一句。这条线

page.status_code.should = '404'

应该是

page.status_code.should == 404

这对我有用 capybara-webkit.


21
投票
Selenium 驱动程序当前不支持

status_code
。您将需要编写不同的测试来检查响应状态代码。


3
投票

要么切换到另一个驱动程序(如

rack-test
)进行该测试,要么测试显示的页面是 404 页面(应该在 h1 中包含“未找到”内容)。

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


3
投票

Selenium 网络驱动程序不实现 status_code 并且没有直接的方法来测试 response_code 与 selenium(开发者的选择)。

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

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

然后在我的测试中:

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

2
投票

试一试

expect(page).to have_http_status(200)

0
投票

使用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

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


0
投票
expect(page).to have_http_status(:ok)

Ajayanswer 的可接受变体,如果您更喜欢状态符号而不是代码值,以便于阅读。

参考资料:

对于所有可用的状态代码/符号:

Rack::Utils::SYMBOL_TO_STATUS_CODE
       # or 
Rack::Utils::HTTP_STATUS_CODES
© www.soinside.com 2019 - 2024. All rights reserved.