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

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

问题描述

如何测试一个 div 标签是否具有某种 css 样式?我正在尝试测试它是否具有 display:none;display:block.

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

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

解决方案

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

通过这种方式,您可以在保持类不变的同时更改底层 css 样式,并且您的测试仍将通过.

寻找底层风格很脆弱.风格经常变化.基于查找特定样式元素的 rspecs 会使您的测试更加脆弱 -- 当您所做的只是更改 div 的外观和感觉时,它们更有可能失败.

基于查找 css 类的测试使测试更加健壮.它允许他们确保您的代码正常工作,同时不需要您在更改页面样式时更改它们.

特别是在这种情况下,一种选择可能是定义一个名为 .hidden 的 css 类,该类在元素上设置 display:none; 以隐藏它.

像这样:

CSS:

.hidden {显示:无;}

html:

水豚:

它{应该有_css('div.hidden')}

这个水豚只寻找一个具有 hidden 类的 div —— 如果需要,你可以让这个匹配器更复杂.

但重点是——将样式附加到 css 类名,然后将您的测试绑定到类,而不是样式.

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/)}

解决方案

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

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

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.

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.

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.

Like this:

css:

.hidden {
  display:none;
}

html:

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

capybara:

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

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

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

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

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