在 rspec 功能场景中,我有:
scenario 'shows things', js: true do
page.find('#my_div').trigger(:click)
这似乎不会触发该元素的 click 事件上的 jQuery 处理程序。在调试器中,此调用返回一个空字符串“”。
capybara-webkit 是否应该能够使用触发更新 dom 的 ajax 请求的 jQuery 处理程序来模拟鼠标事件?如果是这样,对这种情况有什么建议吗?我从 selenium-webdriver 切换,因为不支持 capybara #trigger 方法。
并且尝试直接触发jQuery事件会抛出错误:
page.execute_script "$('#masthead .fclass').trigger('click')"
给
Capybara::Webkit::InvalidResponseError:
Javascript failed to execute
我的 gemfile 有
group :test do
gem 'capybara'
gem "database_cleaner", "~> 0.9.1"
gem 'capybara-webkit', git: 'git://github.com/thoughtbot/capybara-webkit.git'
gem 'launchy'
end
我正在使用'edge' capybara-webkit,因为我遇到了一个带有xpath错误的错误(v2.04?)。
尽管我尝试在 spec/spec_helper.rb 中添加机架异常,但我无法获取 javascript 错误的日志:
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'capybara/rspec'
require 'rack/utils'
Capybara.app = Rack::ShowExceptions.new(MyApp::Application)
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
#...
Capybara.javascript_driver = :webkit
config.before (scope = :suite) do
%x[bundle exec rake assets:precompile]
end
config.use_transactional_fixtures = false
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.before(:each) do
DatabaseCleaner.clean
end
config.infer_base_class_for_anonymous_controllers = false
end
更新: 我将 capybara-webkit 替换为
gem 'poltergeist'
在 spec/spec_helper.rb 中:
require 'capybara/poltergeist'
...
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, { debug: true })
end
Capybara.javascript_driver = :poltergeist
Capybara.current_driver = :poltergeist
我从页面(“#my_id”).trigger('click')的控制台中收到这些错误消息:
...
{"name"=>"click", "args"=>[3, 2]}
poltergeist [1366370900594] state default -> mouse_event
poltergeist [1366370900596] state mouse_event -> loading
Not allowed to load local resource: file:///home/me/rails/my_app/public/assets_test/application.css
...
Not allowed to load local resource: file:///home/me/rails/my_app/public/assets_test/application.js
我试图对 poltergeist gem 权限进行 chmod,但结果相同。
并尝试运行 page.execute_script(%Q($("my_id").trigger('click'))) 给出 jQuery 未定义类型错误:
ReferenceError: Can't find variable: $
at phantomjs://webpage.evaluate():1
at phantomjs://webpage.evaluate():1
at phantomjs://webpage.evaluate():1
at phantomjs://webpage.evaluate():1