How to click first link in list of items after upgrading to Capybara 2.0?

后端 未结 7 1015
抹茶落季
抹茶落季 2020-12-12 15:11

How to click first link in that case:

Agree
相关标签:
7条回答
  • 2020-12-12 15:48

    Simple you can use:

    $('.item').find('a').first().click();
    
    0 讨论(0)
  • 2020-12-12 15:51

    Xpath can address the element. I'm not very good with it yet, but something like //div[@class='active'][1]/a

    That may or may not work, but the point is that xpath can address an array of matches and pull out a particular one. You should be able to match with this.

    A working example example from one of my projects:

    within page.find("div.panel", text: /Proposals/) do
      within page.find('tr', text: /Foo/) do
        page.should have_xpath('td[3]', text: @today)
      end
    end
    
    0 讨论(0)
  • 2020-12-12 15:52

    This phrasing also works:

    within first(".item") do
      click_link "Agree"
    end
    
    0 讨论(0)
  • 2020-12-12 15:52

    most of those solutions will not use Capybara's brilliant waiting features

    better do as this link suggests:
    https://thoughtbot.com/blog/write-reliable-asynchronous-integration-tests-with-capybara#find-the-first-matching-element

    Bad:

    first(".active").click
    If there isn’t an .active element on the page yet, first will return nil and the click will fail.

    Good:

    If you want to make sure there's exactly one
    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.

    0 讨论(0)
  • 2020-12-12 16:00

    Since first() doesn't always wait, perhaps this is useful:

    expect(page).to have_css("selector")                               
    first("selector").click
    
    0 讨论(0)
  • 2020-12-12 16:09

    Try the following:

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

    Sources:

    • http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Node/Actions#click_link-instance_method
    • https://github.com/jnicklas/capybara#strategy
    0 讨论(0)
提交回复
热议问题