Check the dimensions of an img with RSpec/Capybara?-Collection of common programming errors

I’m trying to test the dimensions of an img tag without explicit “height” and “width” attributes, but I’m not sure how to do that exactly.

subject { page }

describe "profile page" do
  let(:user) { FactoryGirl.create(:user) }
  before { visit user_path(user) }

  describe "gravatar image" do
    it "should exist" do
      expect(page.first(".gravatar")).not_to be nil
    end

    it "should be 50x50" do
      gravatar = page.first(".gravatar")
      expect(gravatar[:height]).to eq(50)
      expect(gravatar[:width]).to eq(50)
    end
  end
end

The test for existence works, but the dimension test tells me that the attributes “height” and “width” are nil, which I can sort of understand because I never set them explicitly. But how do I get the actual height/width of an image?

  1. You can use a combination of evaluate_script and client side javascript to get that result:

    page.evaluate_script("$('img')[0].clientHeight")
    

    This would require that your test is executed via a JS runtime like poltergeist etc.