IT story

Capybara 2.0으로 업그레이드 한 후 항목 목록에서 첫 번째 링크를 클릭하는 방법은 무엇입니까?

hot-time 2020. 7. 11. 09:34
반응형

Capybara 2.0으로 업그레이드 한 후 항목 목록에서 첫 번째 링크를 클릭하는 방법은 무엇입니까?


이 경우 첫 번째 링크를 클릭하는 방법 :

<div class="item">
  <a href="/agree/">Agree</a>
</div>
<div class="item">
  <a href="/agree/">Agree</a>
</div>
within ".item" do
  first(:link, "Agree").click
end

이 오류가 발생합니다.

Capybara::Ambiguous:
  Ambiguous match, found 2 elements matching css ".item"

그리고 within내가 없으면 이 오류가 발생합니다.

Failure/Error: first(:link, "Agree").click
NoMethodError:
  undefined method `click' for nil:NilClass

당신은 단지 사용할 수 있습니다 :

first('.item').click_link('Agree')

또는

first('.item > a').click

(기본 선택기가 : css 인 경우)


질문의 코드는 다음과 같이 작동하지 않습니다.

within ".item" do
  first(:link, "Agree").click
end

다음과 같습니다.

find('.item').first(:link, "Agree").click

Capybara는 몇 가지를 발견 .item하여 예외를 발생시킵니다. Capybara 2의이 동작이 매우 좋다고 생각합니다.


다음을 시도하십시오 :

within ".item" do
  click_link("Agree", :match => :first)
end

출처 :


이 문구도 작동합니다.

within first(".item") do
  click_link "Agree"
end

Xpath는 요소를 처리 할 수 ​​있습니다. 아직 잘 못하지만//div[@class='active'][1]/a

그것은 작동하거나 작동하지 않을 수 있지만 요점은 xpath가 일치하는 배열을 처리하고 특정 배열을 가져올 수 있다는 것입니다. 이것과 일치 할 수 있어야합니다.

내 프로젝트 중 하나의 실제 예 :

page.find ( "div.panel", text : / Proposals /) 내에
  page.find ( 'tr', text : / Foo /) 내에
    page.sh_ have_xpath ( 'td [3]', 텍스트 : @today)
  종료
종료

first ()가 항상 기다리는 것은 아니기 때문에 아마도 이것이 유용 할 것입니다 :

expect(page).to have_css("selector")                               
first("selector").click

이러한 솔루션의 대부분은 Capybara의 화려한 대기 기능을 사용하지 않습니다

이 링크가 제안하는 것처럼 더 잘 하십시오 :
https://thoughtbot.com/blog/write-reliable-asynchronous-integration-tests-with-capybara#find-the-first-matching-element

나쁜:

first(".active").click
페이지에 .active 요소가 없으면 먼저 nil을 반환하고 클릭이 실패합니다.

좋은:

정확히 하나 있는지 확인하려면
find(".active").click

If you just want the first element
find(".active", match: :first).click
Capybara will wait for the element to appear before trying to click.

Note that match: :first is more brittle, because it will silently click on a different element if you introduce new elements which match.


Simple you can use:

$('.item').find('a').first().click();

참고URL : https://stackoverflow.com/questions/14513377/how-to-click-first-link-in-list-of-items-after-upgrading-to-capybara-2-0

반응형