RSpec expectations check CSS attribute

2.1k views Asked by At

Could you help me to create a correct RSpec expectation for check CSS attribute?

for example I have:

<td class="MenuItem">

And MenuItem has an atribute "background-color: #c0c0c0".

I need to check that background-color equals to #c0c0c0.

My Example:

expect(page.td_element(:class => "MenuItem").attribute(class).MenuItem).to be == "#c0c0c0"
1

There are 1 answers

1
Justin Ko On BEST ANSWER

In Watir-Webdriver, the Element#style method can be used to get an element's computed style. The computed style is the element's appearance based on style sheets and their style attribute.

Assuming the HTML is like:

<html>
  <head>
    <style>
      .MenuItem { background-color: #c0c0c0; }
    </style>
  </head>
  <body>
    <table>
      <tr>
        <td class="MenuItem">menu</td>
      </tr>
    </table>
  </body>
</html>

We can call the style method and specify the specific property, in this case 'background-color', that we are interested in:

p browser.td(:class => "MenuItem").style('background-color')
#=> "rgba(192, 192, 192, 1)"

The above shows what is returned by Firefox, Chrome and IE. It is possible that other browsers may format the property differently. As you can see, we get back an RGBA rather than the original hex code. While you could write an algorithm to convert the RGBA to a hex code, it is properly easier to test the RGBA code (since that is what is returned).

In terms of writing the RSpec expectation, we are just comparing a String and so can do:

expect(browser.td(:class => "MenuItem").style('background-color')).to eq('rgba(192, 192, 192, 1)')

However, given that you are using the page-object gem, you will need to use cell_element instead of td:

expect(page.cell_element(:class => "MenuItem").style('background-color')).to eq('rgba(192, 192, 192, 1)')