5

我正在使用 rails 2.3.5,这就是我所做的。我安装了最新的黄瓜、黄瓜导轨和水豚。

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 时,我会看到一个确认页面。但是在我点击之前什么都没有发生。

我需要做什么才能自动单击“确定”并继续进行测试。

4

3 回答 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。因此,您不必自己单击“确定”按钮。

于 2010-05-30T20:14:18.807 回答
2

I've implemented a variation on Tobias's solution.

I wanted to have steps like When I follow the "Delete" link for customer "Alice Angry", so I have the following:

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)

The full explanation can be found in the blog post I wrote about it here http://davidsulc.com/blog/2011/07/10/cucumber-tweaks/ (including a helpful step definition for testing content within HTML containers).

于 2011-07-10T20:30:16.690 回答
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
于 2010-11-05T05:42:40.937 回答