如何解决在带有 assert_select 的 Rails 6 集成测试中找不到特定的表行 - 总是找到标题行
我使用 Rails 6.1.0 和 Minitest 5.14.2。
我有一个控制器 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
但测试失败,明确选择标题行并失败:
# 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 中找不到测试文本约束的行,所以我无法确认。
测试输出有点混乱,因为 rails-dom-testing gem 添加了一个隐式 :minimum
约束(因此 Expected 0 to be >= 1.
)并显示第一个匹配选择器的文本(我的case) 当不满足文本约束时(因此 <Janetta Rogahn JD Building> expected but was <Name>..
)。
用正则表达式包装文本:
assert_select('tr',/#{@buildings[0].name}/)`
测试带有文本的表格单元格也是如此:
assert_select('td',@buildings[0].name)`
我希望这能在未来为其他人节省一些时间!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。