Is there a way to Test (Unit/Integration) that CSS is applied to the expected HTML Elements? Is there a way to Test (Unit/Integration) that CSS is applied to the expected HTML Elements? selenium selenium

Is there a way to Test (Unit/Integration) that CSS is applied to the expected HTML Elements?


Sometimes the requirement is that an element is a certain color. It is possible to test this with tools such as Jasmine, but since you want to validate the final display is right, a browser-based integration test is the right tool. (To get this to work in Jasmine, you'd have to do quite a bit more work and end up with a less valid test... anyway...)

I wrote a simple jQuery plugin called Color Spy to be able to query an element about its colors. You can ask:

$(...).backgroundColor()$(...).colorColor()

The plugin traipses up the DOM calculating the color.

To get this to work within the context of a selenium test, you will need to:

  1. make sure the plugin is available. You can just include this in your page, or there are various ways to pull this in dynamically.
  2. write an element_color(selector) test helper function. This will need to use the whole get_eval shenanigans to execute some Javascript dynamically.
  3. Use assert_equal as normal. (I also have some Javascript function in my jsutils repo to assert "visual closeness" of colors-- but that's a different question.)

Hope this helps.


I can understand why you might want to check that the correct id or class has been applied to an element, but I can't see why you'd want to check it's css directly? That'll be so brittle - simply changing the shade of the colour will break your tests!

Also, I think you're missing cucumber's main strength - testing behaviour, not implementation. You should have a read of this - it makes some good points which are pertinent to the way you're currently testing.

In answer to your actual question, if you really want to do this, the only way I can think of is to execute javascript on the page to test the values. This can be done in selenium (with get eval). The same thing can be achieved through capybara so long as the js driver is working.


You could use Webrat (which uses Nokogiri) to test the HTML body response: http://cheat.errtheblog.com/s/webrat/

Then you can do:

assert_have_selector "#content.white"