![](/img/trans.png)
[英]Rails Functional Test assert_select finds nothing after AJAX post
[英]Can't find specific table row in Rails 6 integration test with assert_select - always finds the header row
我正在使用带有 Minitest 5.14.2 的 Rails 6.1.0。
我有一个 controller app/controllers/buildings_controller.rb
:
class BuildingsController < ApplicationController
def index
@buildings = Building.order(:name)
end
end
和一个视图app/views/buildings/index.html.haml
:
%table.table.table-striped
%thead
%tr
%th{scope: 'col'} Name
%th{scope: 'col'}
%tbody
- if @buildings.any?
- @buildings.each do |building|
%tr
%td= building.name
%td.text-right= link_to(icon('fas', 'pencil-alt', 'Edit'), edit_building_path(building), class: 'btn btn-index-action')
- else
%tr
%td.empty-row{colspan: 2} Nothing to show
和一个包含测试的测试文件test/buildings/index_test.rb
shows the building name
,旨在表明页面上存在一行,其中包含在设置中创建的建筑物之一的名称:
require 'test_helper'
class BuildingsControllerTest < ActionDispatch::IntegrationTest
setup do
@user = FactoryBot.create(:user, :staff)
@buildings = FactoryBot.create_list(:building, 5)
sign_in(@user)
end
#...
test 'shows the building name' do
get(buildings_path)
assert_response(:success)
assert_select('tr', text: @buildings[0].name)
end
#...
end
但是测试失败了,显然选择了 header 行并且失败了:
# Running:
F
Failure:
BuildingsControllerTest#test_shows_the_building_name [/app/test/integration/buildings/index_test.rb:37]:
<Nakia Kuvalis Institute> expected but was
<Name>..
Expected 0 to be >= 1.
rails test test/integration/buildings/index_test.rb:33
Finished in 1.835443s, 0.5448 runs/s, 1.0897 assertions/s.
1 runs, 2 assertions, 1 failures, 0 errors, 0 skips
我试过assert_select('tr', @buildings[0].name)
并得到相同的结果。 使用assert_match(@buildings[0].name, @response.body)
有效,但我很好奇为什么我不能专门测试给定文本是否存在表行。
在使用 RSpec 和 Capybara 的其他项目中,我会完成expect(page).to have_selector('tr', text: @buildings[0].name)
并且我希望它能够工作。
如何在 Rails 集成测试中做我想做的事?
rails-dom-testing 似乎通过将文本约束与所选元素的全部内容进行比较来测试text
约束。 就我而言,该行中还有一个 Edit 链接,导致断言失败。 相比之下,Capybara 的匹配器会自动将文本包装在正则表达式中。 但是,我在rails-dom-testing中找不到测试文本约束的行,所以我无法确认。
测试 output 有点令人困惑,因为 rails-dom-testing gem 添加了一个隐式:minimum
约束(因此Expected 0 to be >= 1.
)并显示第一个匹配选择器的文本(在我的例子中是 header 行)未满足文本约束(因此<Janetta Rogahn JD Building> expected but was <Name>..
)。
将文本包装在正则表达式中有效:
assert_select('tr', /#{@buildings[0].name}/)`
使用文本测试表格单元格也是如此:
assert_select('td', @buildings[0].name)`
我希望这可以节省其他人的时间!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.