26

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

4 回答 4

41

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.

于 2012-06-29T04:11:50.133 回答
12

You could use has_css? matcher. It can accept :visible options. For more details you can check docs: http://rdoc.info/github/jnicklas/capybara/Capybara/Node/Matchers#has_css%3F-instance_method

For example you can try:

it { should have_css('div.with-some-class', :visible => true) }
于 2012-07-02T07:03:04.143 回答
9

My way to ensure that element have a certain class:

let(:action_items) { page.find('div.action_items') }

it "action items displayed as buttons" do
  action_items.all(:css, 'a').each do |ai|
    expect(ai[:class]).to match(/btn/)
  end
end

or smthing like this

expect(ai[:style]).to match(/color: red/)

I found it here: http://rubydoc.info/github/jnicklas/capybara/Capybara/Node/Element#%5B%5D-instance_method

于 2014-06-10T10:21:00.343 回答
2

You can use Capybara's assert_matches_style, or the Rspec HaveStyle matcher (which is using assert_matches_style underneath):

When you use assert_matches_style directly, it's:

find(".element").assert_matches_style("font-size" => "46px")

I'm not too familiar with Rspec syntax, but it should be something like this:

it { should match_style("font-size" => "46px") }
于 2020-07-03T09:23:33.630 回答