Reputation: 221
I'm trying to write test the value of alt text + src of an image using capybara and the css selectors.
any idea s to test both in single xpath ?
Upvotes: 22
Views: 18661
Reputation: 8418
In 2022, this works perfectly:
find("img[src='https://some-url.com/image.jpg']")
or with embedded ruby
find("img[src='#{@post.image}']")
Here is an example I recently used:
test "Showing a company" do
visit companies_path
click_link @company.name
assert_title @company.name
assert_selector :link, href: @company.url
assert_selector "h3", text: @company.title
assert_selector "p", text: @company.description
find("img[src='#{@company.image}']")
end
Upvotes: 1
Reputation: 101
Should
is a bit out dated. Expect
is RSpec's new expectation syntax.have_content
as much as possible since it is not exactly verifying the value of the attribute that I want and just performs a HaveText(*args)
. It can cause false positives.
before(:all) do
@avatar_image = find('#profile-avatar')
end
it 'has correct src' do
expect(@avatar_image[:src]).to eq("some_url")
end
it 'has correct alt text' do
expect(@avatar_image[:alt]).to eq("some_text")
end
Upvotes: 3
Reputation: 2708
You can check multiple attributes using xpath
assert page.has_xpath("//img[@src = 'some_value' and @alt='some_value']")
Upvotes: 8
Reputation: 6700
A slightly simpler way will be to use an id for that image:
page.find('#profile-avatar')['src'].should have_content 'default.png'
Updated for rspec 3:
expect(page.find('#profile-avatar')['src']).to have_content 'default.png'
expect(page.find('#profile-avatar')['alt']).to match(/some-value/)
Upvotes: 35
Reputation: 265
variable=find(:xpath, "//img[@class='class_name']")
variable['src'].should == "url"
variable['alt'].should == "text"
Upvotes: 7
Reputation: 51
It does not answer directly your question but if some people fancy debugging ease over speed, I'd suggest using this syntax :
find(:xpath, "//img[@class='avatar']/@src").text.should match /some url/
find(:xpath, "//img[@class='avatar']/@alt").text.should match /some text/
as the error will be more explicit if it fails. (it will actually display the value of src
and alt
).
Upvotes: 1
Reputation: 1383
I was having some trouble because the src of my image had some dynamic values, so I did this:
find(locator+' img')['src'].include?(img_src).should be_true
I don't really care about the path, just if the file name was the correct
Upvotes: 1