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