Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

capybara selenium and JavaScript Destroy

I am using rails 2.3.5 and this is what I did. I have latest cucumber, cucumber-rails and capybara installed.

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

All the tests are passing. Now I want to test using Javascript.

At this time this is how scenario looks like

  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|

I added @javascript at the top.

Now when I run rake cucumber then I see a confirmation page. But nothing happens until I click.

What do I need to do so that OK is clicked automatically and test proceeds ahead.

like image 880
Nick Vanderbilt Avatar asked May 13 '10 16:05

Nick Vanderbilt


2 Answers

Well its kind of a hack, but I think right now its the only way:

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

You have to put this step right in front of the one that triggers the confirm popup (follows the link). It will modify the standard alert and confirm behaviour to always return true. So you do not have to click the "OK" button yourself.

like image 97
spas Avatar answered Sep 29 '22 12:09

spas


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).

like image 25
David Sulc Avatar answered Sep 29 '22 10:09

David Sulc