Rails 5 Capybara 未创建已点击按钮

Rails 5 Capybara not founding already clicked button

我有以下测试:

  it 'shows the current quantity of items inside cart' do
    item = create(:item)
    visit root_path
    click_link("add-item-#{item.id}")
    wait_for_ajax
    page.find('#notice-modal-ok').click
    click_link("add-item-#{item.id}")
    wait_for_ajax
    page.find('#notice-modal-ok').click
    expect(page).to have_selector('#cart-item-count', text: '2')
  end

它基本上是一个带有 ajax 的按钮,当 return 状态为 200 时显示成功模式。但是,当第二个 ajax 发生时,由于我无法理解的原因,模态没有出现。我可以在开发环境中正常执行此操作。 感谢您的帮助!


编辑#1

我添加了一个 save_and_open_screenshot 来尝试调试它。最后的代码看起来是这样的:

  it 'shows the current quantity of items inside cart' do
    item = create(:item)
    visit root_path
    click_link("add-item-#{item.id}")
    page.find('#notice-modal-ok', wait: 10).click
    expect(page).not_to have_selector('#notice-modal-ok')
    click_link("add-item-#{item.id}")
    save_and_open_screenshot # image
    page.find('#notice-modal-ok', wait: 10).click # this fails
    expect(page).to have_selector('#cart-item-count', text: '2', wait: 10)
  end

图片编号 1

如图所示,模态框在第二次调用时没有出现。这是显示它的 javascript:

  $(document).ready(function() {
    $("a:regex(id,add-item-[0-9]+)").click(function(event) {
      event.preventDefault();
      var link = $(this).attr("href");

      $.ajax({
        url: link,
        method: "GET",
        dataType: "json",
        success: function(data) {
          $('#notice-modal').modal('show');
          if(data.quantity) {
            $("#cart-item-count").css('display', 'block');
            $("#cart-item-count").html(data.quantity);
          } else {
            $("#cart-item-count").hide()
          }
        }
      });
    })
  });

并且在开发模式下,正常运行。希望这些新信息对您有所帮助!

首先,如果 ID 为 'notice-modal-ok' 的元素仅在 ajax 请求完成后出现,则不需要 wait_for_ajax。除此之外,假设单击模式不会影响添加项的行为 link,则有几种可能性。一是在 link 单击发生之前模态框实际上并没有消失,这抑制了 link 行为。另一个可能是 `Capybara.default_max_wait_time' 没有设置得足够高以适应您 运行 所使用的硬件。要测试这些,您可以在第二次单击 link 之前等待模态消失,并暂时增加最长等待时间

更新: 问题的根本原因是 semantic-ui 认为如果您单击 'ok' 按钮在它完全动画到位之前将其关闭。在测试中解决这个问题的方法是在单击 ok 按钮之前确保模式具有 class 'active'。另一种解决方案是在测试时禁用 semantic-ui 中的所有动画(如果有该选项),这也会加快测试速度。

it 'shows the current quantity of items inside cart' do
  item = create(:item)
  visit root_path
  click_link("add-item-#{item.id}")
  page.find('#notice-modal.active #notice-modal-ok').click
  expect(page).not_to have_selector('#notice-modal') #verify/wait for the modal to disappear
  click_link("add-item-#{item.id}")
  page.find('#notice-modal.active #notice-modal-ok').click
  expect(page).to have_selector('#cart-item-count', text: '2')
end