开发者

How do I test an image src and alt value using capybara?

开发者 https://www.devze.com 2023-03-15 13:57 出处:网络
I\'m trying to writetest the value of alt text + src of an image using capybara and the css selectors.

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 x开发者_如何转开发path ?


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/)


variable=find(:xpath, "//img[@class='class_name']")
variable['src'].should == "url"
variable['alt'].should == "text"


You can check multiple attributes using xpath

assert page.has_xpath("//img[@src = 'some_value' and @alt='some_value']")


  1. Should is a bit out dated. Expect is RSpec's new expectation syntax.
  2. Separating expectations in their own specs is good practice.
  3. Personal preference: I avoid 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


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


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).


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号