如何测试div在rspec / capybara中是否具有特定的CSS样式? [英] How do you test if a div has a certain css style in rspec/capybara?

查看:28
本文介绍了如何测试div在rspec / capybara中是否具有特定的CSS样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何测试div标签是否具有特定的CSS样式?我正在尝试测试它是否具有 display:none; display:block

How do you test if a div tag has a certain css style? I'm trying to test if it has display:none; or display:block.

我尝试了以下操作,但给了我一个错误:

I tried the following but its giving me an error:

it {should have_selector('signup_server_generic_errors', /display:\s*none/)}


推荐答案

我建议您不要尝试查找css样式,而是编写测试以找到 css类名

I'd recommend that instead of trying to locate the css style, you instead write your tests to find the css class name.

这样,您可以在更改基础CSS样式的同时保持类不变,并且测试仍将通过。

This way you can change the underlying css styling while keeping the class the same and your tests will still pass.

搜索基础样式是脆。样式经常变化。将rspec建立在查找特定样式元素的基础上会使您的测试更加脆弱-当您所做的只是更改div的外观时,它们很可能会失败。

Searching for the underlying style is brittle. Styles change frequently. Basing your rspecs on finding specific style elements makes your tests more brittle -- they'll be more likely to fail when all you do is change a div's look and feel.

将测试建立在寻找CSS类的基础上,可以使测试更加可靠。

Basing your tests on finding css classes makes the tests more robust. It allows them to ensure your code is working correctly while not requiring you to change them when you change page styling.

在这种情况下,一种选择可能是定义一个代码,这样可以确保代码正确工作,而无需在更改页面样式时进行更改。名为 .hidden 的CSS类,将 display:none; 设置为隐藏它的元素。

In this case specifically, one option may be to define a css class named .hidden that sets display:none; on an element to hide it.

就像这样:

css:

.hidden {
  display:none;
}

html:

<div class="hidden">HIDE ME!</div>

水豚:

it {should have_css('div.hidden') }

这只水豚看起来像对于具有隐藏类的div -如果需要,可以使此匹配器更加复杂。

This capybara just looks for a div that has the hidden class -- you can make this matcher more sophisticated if you need.

但是主要要点是-将样式附加到CSS类名称,然后将测试绑定到类而不是样式。

But the main point is this -- attach styles to css class names, then tie your tests to the classes, not the styles.

这篇关于如何测试div在rspec / capybara中是否具有特定的CSS样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆