【发布时间】:2012-07-03 17:39:31
【问题描述】:
我正在编写 Capybara 测试并使用 Rspec 进行断言。我的测试失败了,因为应用了一种 CSS 样式导致文本全部大写。我该如何重写它以使其成为不区分大小写的断言?
"ALL CAPS".should include('All Caps')
【问题讨论】:
标签: ruby rspec capybara case-insensitive
我正在编写 Capybara 测试并使用 Rspec 进行断言。我的测试失败了,因为应用了一种 CSS 样式导致文本全部大写。我该如何重写它以使其成为不区分大小写的断言?
"ALL CAPS".should include('All Caps')
【问题讨论】:
标签: ruby rspec capybara case-insensitive
以下是对 phoet 解决方案的改进:
page.body.should match(%r{#{string}}i)
不幸的是,这里的语法突出显示并不太公平(在 Sublime Text 中看起来非常好)
【讨论】:
page.find 'li.line-item', text: %r{Awesome Line Item}i
page.find 'li.line-item', text: /#{Awesome Line Item}/i 如果您更喜欢斜杠语法。 (在 Sublime Text 中的正则表达式周围添加括号以获得正确的语法突出显示。)
我只在以下情况下遇到这个问题:
使用 poltergeist 驱动程序。 (不知道其他司机是否也会出现这种情况)
检查 page,而不是 page.body 的期望:expect(page).to ...
所以,如果我这样做 expect(page.body).to ... 它就可以解决问题。
【讨论】:
如何使用正则表达式来做到这一点?
"ALL CAPS".should match(/#{Regexp.escape('All Caps')}/i)
【讨论】:
如何降低断言的两端?
"ALL CAPS".downcase.should include('All Caps'.downcase)
【讨论】:
Rspec 语法在 4 年内发生了显着变化,但这个潜在的问题似乎仍然是个问题。我的解决方案是构建一个自定义匹配器has_content_i,它类似于has_content,但不区分大小写。结果调用如下所示:
expect(page).to have_content_i("All Caps")
来源:
RSpec::Matchers.define :have_content_i do |expected|
match do |actual|
actual.text =~ /#{Regexp.quote expected}/i
end
failure_message do |actual|
"expected to find text #{expected.inspect} case insensitively in #{actual.text.inspect}"
end
failure_message_when_negated do |actual|
"expected to not to find text #{expected.inspect} case insensitively in #{actual.text.inspect}"
end
end
http://danielchangnyc.github.io/blog/2014/01/15/tdd2-RSpecMatchers/ 提供有关将自定义匹配器定义存储在项目树中的位置的信息。
【讨论】:
另外,如果您使用 Capybara,您可以使用不区分大小写的 have_content 匹配器:
<h1>ALL CAPS</h1>
find('h1').should have_content('All Caps')
更新:我想我部分错了。考虑一下:
<h1 style="text-transform: uppercase">Title Case</h1>
puts find('h1').text
# TITLE CASE < notice all caps
puts find('h1').has_content?('Title Case') # true
puts find('h1').has_content?('TITLE CASE') # false
puts find('h1').has_content?('title case') # false
让我感到奇怪的是,返回的文本全部大写(它在 CSS 之后的样式),但匹配器实际上是针对无样式 HTML 中的文本进行测试。我花了一段时间挖掘源代码,但仍然无法弄清楚为什么会这样。
【讨论】:
puts find('h1').text 和/或puts find('h1').inspect 核对一下,看看到底发现了什么。最后,我得到了'ALL CAPS',这在你的例子中正确地失败了。