Capybara、Selenium和JavaScript的销毁

5

我正在使用rails 2.3.5版本,并采取了以下步骤。我已经安装了最新的cucumber、cucumber-rails和capybara。

rails demo
cd demo
ruby script/generate cucumber --rspec --capybara
ruby script/generate feature post title:string body:text published:boolean
ruby script/generate scaffold post title:string body:text published:boolean
rake db:migrate
rake cucumber

所有测试都通过了。现在我想使用Javascript进行测试。

此时,场景看起来是这样的:

  Scenario: Delete post
    Given the following posts:
      |title|body|published|
      |title 1|body 1|false|
      |title 2|body 2|true|
      |title 3|body 3|false|
      |title 4|body 4|true|
    When I delete the 3rd post
    Then I should see the following posts:
      |Title|Body|Published|
      |title 1|body 1|false|
      |title 2|body 2|true|
      |title 4|body 4|true|

我在顶部添加了@javascript。现在当我运行rake cucumber时,我会看到一个确认页面。但是除非我点击,否则什么也不会发生。
我需要做什么才能自动点击“OK”并使测试继续进行。
3个回答

8

这有点像一个技巧,但我认为现在这是唯一的方法:

When /^I confirm a js popup on the next step$/ do
  page.evaluate_script("window.alert = function(msg) { return true; }")
  page.evaluate_script("window.confirm = function(msg) { return true; }")
end

你需要将这个步骤放在触发确认弹窗(跟随链接)之前。它会修改标准的提示和确认行为,始终返回true。因此,您不必自己点击“确定”按钮。


2

我对Tobias的解决方案进行了改进。

我希望像这样使用步骤:当我点击“删除”链接,选择客户“Alice Angry”,因此我有以下内容:

When /^(.*) and (?:|I )click "OK"$/ do |step|
  click_ok_after { When step }
end

module JavascriptHelpers
  def click_ok_after
    begin
      page.evaluate_script("window.alert = function(msg) { return true; }")
      page.evaluate_script("window.confirm = function(msg) { return true; }")
    rescue Capybara::NotSupportedByDriverError
      # do nothing: we're not testing javascript
    ensure
      yield
    end
  end
end
World(JavascriptHelpers)

完整的解释可以在我写的博客文章中找到,链接在这里http://davidsulc.com/blog/2011/07/10/cucumber-tweaks/(包括一个有用的步骤定义来测试HTML容器内的内容)。


0
由于Steven提供的解决方案,特此感谢。这是我对其稍作修改以使其更易读的方法:
When /^I follow "([^"]*)" and click OK$/ do |text|
  page.evaluate_script("window.alert = function(msg) { return true; }")
  page.evaluate_script("window.confirm = function(msg) { return true; }")
  When %{I follow "#{text}"}
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接