Jquery – $ is not defined error in Selenium test

capybarajqueryruby-on-railsseleniumselenium-webdriver

I'm trying to test jQuery autocomplete in a Rails 3.2 app using Selenium. Following this blog post I've created a fill_autocomplete helper method that looks like this:

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

When I run RSpec, I get this error:

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

The problem line is 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

dev/test group of 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

I've tried downgrading RSpec, Capybara, and Selenium-Webdriver. I've tried using Capybara-Webkit instead of Selenium. All to no avail.

I've been working under the assumption that jQuery autocomplete hooks into the 'keydown' event and that Capybara's fill_in doesn't trigger this event on it's own. Is this correct?

Any solution or workaround is welcome. Thanks!

Best Answer

Thanks to Arran's advice I realized that an error elsewhere in the JS was happening before JQuery could be defined.

Related Topic