我正在使用Capybara和Minitest来测试我的Rails 4应用程序。我们正在尝试测试一个页面,该页面通过AJAX加载Google地图和颜色框。
我们需要先检查AJAX是否已加载,然后再检查某个元素并尝试遵循本教程:https://thoughtbot.com/blog/automatically-wait-for-ajax-with-capybara
大多数教程都使用RSpec,所以我将代码放入test_helper.rb
:
class ActionDispatch::IntegrationTest
# Make the Capybara DSL available in all integration tests
include Capybara::DSL
include Warden::Test::Helpers
Warden.test_mode!
Capybara.default_max_wait_time = 5
Capybara.javascript_driver = :webkit
def wait_for_ajax
page.evaluate_script("jQuery.active") == 0
yield
end
end
[查看出现错误的其他人,看来他们没有安装capybara-webkit
gem。但是,我们这样做:
正在运行bundle install
:
...
Using capybara 2.5.0
Using capybara-webkit 1.7.1
这是我失败的测试:
test "colorbox should appear on pageload" do
visit trips_new_path
wait_for_ajax do
assert_selector "#colorbox", "colorbox not created on trips/new"
end
end
并且我收到错误:
Capybara::NotSupportedByDriverError: Capybara::NotSupportedByDriverError: Capybara::Driver::Base#evaluate_script
test/test_helper.rb:35:in `wait_for_ajax'
test/integration/trip_creation_test.rb:17:in `block in <class:TripCreationTest>'
我曾尝试在一些不同的地方设置JavaScript,但似乎仍然无法正常工作。
更新:尝试了其他语法并收到相同的错误:
def wait_for_ajax
Capybara.javascript_driver = :webkit
Timeout.timeout(Capybara.default_wait_time) do
loop until finished_all_ajax_requests?
end
end
def finished_all_ajax_requests?
page.evaluate_script('jQuery.active').zero?
end
谢谢您的帮助!
您收到NotSupportedByDriver错误的事实意味着您的测试实际上并未使用capybara-webkit驱动程序,并且可能仍在使用默认的racktest驱动程序。您需要指定特定的测试应该使用支持JavaScript的驱动程序。如果您使用的是https://github.com/wojtekmach/minitest-capybara之类的内容,则可以浏览README中的宝石,以查看有关如何手动指定或进行设置的示例,以便可以使用元数据标记测试。一旦您使用正确的驱动程序进行了测试,您可能会发现实际上并不需要wait_for_ajax方法,因为Capybaras查找器将自动等待内容出现。