在使用 Minitest 测试框架做测试时遇到一些问题,情况如下
个人比较习惯使用 spec 形式,并引入了 Capybara DSL
在写一个测试时,需要进行一个 click_link,而触发一个 ajax 请求,然后对返回的页面进行断言
测试是这样写的:
describe "节目页面跳转相关" do
it "如果未登录,点击预约报名应该跳转至登录页面" do
program = FactoryGirl.create(:program)
# require_js
visit programs_path
click_link "appointment-program-#{program.id}", :href => "#"
# wait_for_ajax
page.must_have_selector 'h1', :text => 'Program Index'
end
end
页面是这样写的:
<ul>
<% @programs.each do |program| %>
<li>
<%= program.title %> <br>
<%= link_to '报名', '#',
:id => "appointment-program-#{program.id}",
:onclick => "programs_index.ajax_post_appoint(#{program.id})" %>
</li>
<% end %>
</ul>
test_helper 是这样的
ENV["RAILS_ENV"] = "test"
require File.expand_path("../../config/environment", __FILE__)
require "rails/test_help"
require "minitest/rails"
require "minitest/rails/capybara"
require "minitest/reporters"
Minitest::Reporters.use!(
Minitest::Reporters::ProgressReporter.new,
ENV,
Minitest.backtrace_filter
)
require 'database_cleaner'
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.clean_with(:truncation)
class ActiveSupport::TestCase
ActiveRecord::Migration.check_pending!
include FactoryGirl::Syntax::Methods
Capybara.default_wait_time = 5
def require_js
Capybara.current_driver = :webkit
end
def wait_for_ajax
Timeout.timeout(Capybara.default_wait_time) do
active = page.evaluate_script('jQuery.active')
until active == 0
active = page.evaluate_script('jQuery.active')
end
end
end
def setup
DatabaseCleaner.start
end
def teardown
DatabaseCleaner.clean
Capybara.reset_session!
Capybara.use_default_driver
end
end
class ActionDispatch::IntegrationTest
include Capybara::DSL
include Capybara::Assertions
end
wait_for_ajax
它不认识,不能执行 JS 方法,因此我查文档后发现要在使用 JS 的地方切换成:webkit
驱动require_js
方法时,即使用 :webkit
驱动后,测试单元测试会变得龟速无比,一个测试要 16s(说好很快的呢)wait_for_ajax
根本都执行不到至此已经研究了好几个小时了,实在是束手无策