我有以下测试:
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 的按钮,当返回状态为 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
。除此之外,假设单击模式不会影响添加项目链接的行为,则有几种可能性。一是在链接点击发生之前模式实际上并没有消失,这抑制了链接行为。另一个可能是“Capybara.default_max_wait_time”没有设置得足够高以适应您正在运行的硬件。要测试这些,您可以在第二次单击链接之前等待模态消失,并暂时增加最长等待时间
更新:问题的根本原因是如果您单击“确定”,semantic-ui
认为模态仍然处于事件状态(即使它已关闭) ' 按钮在它完全动画到位之前将其关闭。在测试中解决这个问题的方法是在单击 ok
按钮之前确保模态具有“事件”类。另一种解决方案是在测试时禁用 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
关于capybara - Rails 5 Capybara 没有建立已经点击的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44741564/