ruby-on-rails – 如何测试rails 4确认对话与Capybara和Poltergeist?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 如何测试rails 4确认对话与Capybara和Poltergeist?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图测试一个链接到一个破坏动作引发一个本地浏览器确认框与正确的消息.

链接正在使用rails’link_to:

link_to 'Delete',user_path,method: :delete,data: { confirm: "Are you sure?" }

生成以下html:

<a data-confirm="Are you sure?" data-method="delete" href="/users/6" rel="nofollow">Delete</a>

功能在浏览器中正常工作,但我想在我的rspec功能规范中进行测试.

我试图清除浏览器的确认功能,如herethis gist所述,但是我无法使其工作.

it 'requests confirmation',js: true do
  visit user_path(user)
  page.execute_script "
    window.confirmMsg = null;
    window.confirm = function(msg) { window.confirmMsg = msg; return true; };"
  click_link 'Delete'
  expect(page.evaluate_script('window.confirmMsg')).to eq('Are you sure?')
end

从rspec发出以下错误

Failure/Error: expect(page.evaluate_script('window.confirmMsg')).to eq('Are you sure?')

       expected: "Are you sure?"
            got: nil

       (compared using ==)

但是,如果我直接通过page.execute_script直接打电话确认:

it 'requests confirmation',js: true do
  visit user_path(user)
  page.execute_script "
    window.confirmMsg = null;
    window.confirm = function(msg) { window.confirmMsg = msg; return true; };
    window.confirm('Are you sure?');"
  expect(page.evaluate_script('window.confirmMsg')).to eq('Are you sure?')
end

然后测试通过.

同时单击删除链接将导致测试失败,即使直接为page.execute_script调用确认:

it 'requests confirmation',js: true do
  visit user_path(user)
  page.execute_script "
    window.confirmMsg = null;
    window.confirm = function(msg) { window.confirmMsg = msg; return true; };
    window.confirm('Are you sure?');"
  click_link 'Delete'
  expect(page.evaluate_script('window.confirmMsg')).to eq('Are you sure?')
end

从rspec发出同样的错误

Failure/Error: expect(page.evaluate_script('window.confirmMsg')).to eq('Are you sure?')

       expected: "Are you sure?"
            got: nil

       (compared using ==)

为什么测试失败?而且,如何正确地测试确认对话?

语境:

我从Vagrant虚拟机运行我的测试,这是Ubuntu 12.04.4 LTS和运行ruby 2.1.2p95.

我的Gemfile.lock显示我有以下版本:

rails (4.1.4)
poltergeist (1.5.1)
capybara (2.4.1)

解决方法

page.driver.browser.accept_js_confirmed已被弃用.而是使用
page.accept_confirm do
  click_link 'Delete'
end
原文链接:https://www.f2er.com/ruby/266926.html

猜你在找的Ruby相关文章