简体   繁体   中英

Execute JavaScript with Cucumber/Capybara tests

I am looking to execute some JavaScript within a after hook in my cucumber tests, what I'm looking to do is capture any JavaScript errors and output the errors within my console.

What I am having trouble with at the moment is using the method execute_script to run a piece of JavaScript

I get the error

undefined method `execute_script' for #<Cucumber::Ast::Scenario:0x5878608> (NoMethodError)

This is my setup so far

Capybara.register_driver :firefox do |app|
  profile = Selenium::WebDriver::Firefox::Profile.new
  # see https://github.com/mguillem/JSErrorCollector
  profile.add_extension "./lib/firefox_extensions/JSErrorCollector.xpi"
  profile.native_events = false
  Capybara::Selenium::Driver.new(app, :browser => :firefox)
end

(Am I adding the extension correctly by specifying the path correctly? using . to start at root?)

My After Hook

After do |page|
  errors = page.execute_script("return window.JSErrorCollector_errors.pump()")

  if errors.any?
    STDOUT.puts '-------------------------------------------------------------'
    STDOUT.puts "Found #{errors.length} javascript #{pluralize(errors.length, 'error')}"
    STDOUT.puts '-------------------------------------------------------------'
    errors.each do |error|
      puts "    #{error["errorMessage"]} (#{error["sourceName"]}:#{error["lineNumber"]})"
    end
    raise "Javascript #{pluralize(errors.length, 'error')} detected, see above"
  end
end

Is there anything I'm doing here that looks incorrect or does anyone do this in a different way?

The After passes a Scenario object (the scenario that just ran) to the block, you've just happened to name the variable page . Frequently, this variable will be called scenario . The undefined_method line is showing what object type ( #<Cucumber::Ast::Scenario:0x5878608> ) the NoMethodError is coming from in the error message.

You should be able to execute code in an After block like you would in any other Cucumber step.

After do |scenario|
  errors = page.execute_script("return window.JSErrorCollector_errors.pump()")

  if errors.any?
    STDOUT.puts '-------------------------------------------------------------'
    STDOUT.puts "Found #{errors.length} javascript #{pluralize(errors.length, 'error')}"
    STDOUT.puts '-------------------------------------------------------------'
    errors.each do |error|
      puts "    #{error["errorMessage"]} (#{error["sourceName"]}:#{error["lineNumber"]})"
    end
    raise "Javascript #{pluralize(errors.length, 'error')} detected, see above"
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM