【发布时间】:2017-07-24 16:49:23
【问题描述】:
Rails 4.2 应用程序的索引视图在其标题处有一个带有排序链接的表。如果用户单击“E-mail”标题,记录将按 E-mail 排序,依此类推。单击排序链接时,将重新加载页面(使用类似q=email+asc 的查询字符串)。尚未使用 AJAX。
我已经编写了以下测试。它有效,但我相信应该有更好的方法来测试它。
it "sorts by e-mail when the 'E-mail' column header is clicked", :focus do
visit "/admin/users"
expected_id_order = User.order(:email).map(&:id)
# Once the page is reloaded (the new sort order is applied), the "stale"
# class will disappear. Note that due to Turbolinks, only the part of
# the DOM that is modified by a request will have its elements replaced.
page.execute_script("$('tr.user:first').addClass('stale')")
within "thead" do
click_link("E-mail")
end
# Force Capybara to wait until the page is reloaded
expect(page).to have_no_selector("tr.user.stale")
actual_id_order = page.body.scan(/<tr.+id="user_(.+)".*>/).flatten
expect(actual_id_order).to eq(expected_id_order)
end
其他细节:
-
<TR>元素的 DOM ID 包含其对应记录的 DB ID,例如<tr class="user" id="user_34">。使用正则表达式提取记录在页面中的显示顺序可能不是最佳解决方案。你能推荐一个更好的方法吗? - 我不喜欢 JavaScript hack(使用 JQuery 添加
stale类,然后等到它消失以确保重新加载页面),但到目前为止我找不到另一种方法来确保 Capybara 等到页面重新加载(应用新的排序顺序)。你能推荐一个更好的方法吗? - 应用程序使用Devise,因此我们需要创建用户记录才能登录。请注意,为登录目的创建的用户不可避免地会出现在我们的测试数据中。
【问题讨论】:
标签: ruby-on-rails ruby testing rspec capybara