【问题标题】:$ is not defined error in Selenium test$ is not defined 硒测试中的错误
【发布时间】:2014-09-18 12:01:32
【问题描述】:

我正在尝试使用 Selenium 在 Rails 3.2 应用程序中测试 jQuery 自动完成功能。在this blog post 之后,我创建了一个fill_autocomplete 辅助方法,如下所示:

def fill_autocomplete(field, options = {})
  fill_in field, with: options[:with]

  page.execute_script %Q{ $('##{field}').trigger('focus') }
  page.execute_script %Q{ $('##{field}').trigger('keydown') }
end

当我运行 RSpec 时,我得到这个错误:

Failure/Error: fill_autocomplete 'crop', with: 'm'
 Selenium::WebDriver::Error::JavascriptError:
   $ is not defined

问题线是page.execute_script %Q{ $('##{field}').trigger('focus') }


spec_helper.rb

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'coveralls'
require 'simplecov'
require 'capybara'

include Warden::Test::Helpers

SimpleCov.configure do
  add_filter 'spec/'
end
Coveralls.wear!('rails')

Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"

  config.use_transactional_fixtures = true

  config.infer_base_class_for_anonymous_controllers = false

  config.order = "random"

  config.include Devise::TestHelpers, :type => :controller
  config.extend ControllerMacros, :type => :controller
end

Gemfile 的开发/测试组

group :development, :test do
  gem 'haml-rails'                     
  gem 'rspec-rails', '~> 2.12.1'       
  gem 'webrat'                         
  gem 'capybara', '~> 2.4.1'            
  gem 'selenium-webdriver', '~> 2.42.0' 
  gem 'factory_girl_rails', '~> 4.0'    
  gem 'coveralls', require: false      
end

我尝试过降级 RSpec、Capybara 和 Selenium-Webdriver。我尝试过使用 Capybara-Webkit 而不是 Selenium。一切都无济于事。

我一直在假设 jQuery 自动完成挂钩到“keydown”事件并且 Capybara 的 fill_in 不会自行触发此事件。它是否正确?

欢迎任何解决方案或解决方法。谢谢!

【问题讨论】:

  • 听起来你没有将 jQuery 映射到 $。所以为了证明这一点,做一个测试:运行你的自动化测试直到它试图触发脚本。到达那里后,停止测试。现在,打开 Chrome/Firefox 的开发工具,然后手动运行相同的脚本。理论上,您应该得到相同的错误。如果是这样,那仅仅是因为$ 并不总是会映射到jQuery(总是假设是非常非常错误的)。
  • 感谢您的调试建议,我发现这是在定义 JQuery 之前发生的 JS 错误。

标签: jquery ruby-on-rails selenium selenium-webdriver capybara


【解决方案1】:

感谢 Arran 的建议,我意识到在定义 JQuery 之前,JS 中的其他地方发生了错误。

【讨论】:

    猜你喜欢
    • 2020-12-03
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    相关资源
    最近更新 更多