Finding images with Capybara

Hi,

I set up my test suite to test for Carrierwave Uploaders using the excellent blogpost:

RSpec and FactoryGirl Setup for Testing Carrierwave Uploaders

then, to test the presence of an image, I use the Capybara have_xpath method:

expect(page).to have_xpath("//img[@src='/Users/acandael/Sites/beautysalonapp2/spec/support/uploads/promotion/image/#{promotion.id}/environ-peeling-kuur.jpg']")

Apparently I have to give the absolute path to the have_xpath method to find the image on the page. Now Iā€™m wondering if there isnā€™t a nicer way to do this, so I only need to give a relative path, something like:

expect(page).to have_xpath("//img[@src='environ-peeling-kuur.jpg']")

thanks for your help,

Anthony

Could you use this? (Iā€™m sure thereā€™s an xpath way to do it, Iā€™m just more familiar with css):

expect(page).to have_css("img[src*='environ-peeling-kuur.jpg']")

The CSS selector img[src*='your value'] is saying "Find 'your value' anywhere in the source of said imageā€¦Ā A better explanation can be found here.

Capybaraā€™s documentation on selectors might not be the best, but try searching for xpath tutorials. That should get you sorted. Hereā€™s one (sorry w3schools link)

1 Like

Does this work?

expect(page).to have_xpath("//img[contains(@src,'environ-peeling-kuur.jpg')]")

I havenā€™t used that syntax in tests but I use it successfully in a scraper that iterates over grocery ad items:

page.all(:xpath,"//div[contains(@id,'CircularListItem')]").each do |node|
1 Like

Hi Chris,

this line works:

expect(page).to have_xpath("//img[contains(@src,'environ-peeling-kuur.jpg')]")

thanks for your suggestion, this is indead a lot cleaner then:

have_xpath("//img[@src='/Users/acandael/Sites/beautysalonapp2/spec/support/uploads/promotion/image/#{promotion.id}/environ-peeling-kuur.jpg']")

to make the file name of the image dynamic in my test, I use:

      expect(page).to have_xpath("//img[contains(@src,'#{File.basename(promotion.image.url)}')]")

greetings,

Anthony

Hi Daniel,

I tried

expect(page).to have_css("img[src*='environ-peeling-kuur.jpg']")

and it worked!

Thatā€™s indeed a lot cleaner.

thanks for your help,

Anthony