问题
I'm writing a Capybara test and using Rspec for the assertions. My test is failing because there is a CSS style being applied that is causing the text to be in all caps. How can I rewrite this so that it is a case insensitive assertion?
"ALL CAPS".should include('All Caps')
回答1:
Here's improving on phoet's solution:
page.body.should match(%r{#{string}}i)
Unfortunately the syntax highlighting here isn't doing it much justice (it looks perfectly fine in Sublime Text)
回答2:
I only run into this issue when:
Using poltergeist driver. (I don't know if this also happens with other drivers)
Inspecting
page
, notpage.body
for expectations:expect(page).to ...
So, If I do expect(page.body).to ...
it just works and solved the issue.
回答3:
how about using a regex to do this?
"ALL CAPS".should match(/#{Regexp.escape('All Caps')}/i)
回答4:
How about downcasing both ends of the assertion?
"ALL CAPS".downcase.should include('All Caps'.downcase)
回答5:
Rspec syntax has changed significantly in 4 years, but this underlying problem still seems like a problem. My solution was to build a custom matcher has_content_i
, which was like has_content
but is case insensitive. The resulting call looks like:
expect(page).to have_content_i("All Caps")
Here's the source:
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/ has information on where to stash the custom matcher definitions in your project tree.
回答6:
Also, if you are using Capybara, you can use the have_content
matcher which is case insensitive:
<h1>ALL CAPS</h1>
find('h1').should have_content('All Caps')
Update: I guess I was partly wrong. Consider this:
<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
It's strange to me that the text returned is in all caps (how it's styled after CSS), but the matcher is actually testing against the text in the unstyled HTML. I spent a while digging through the source code and I still can't figure out why this works.
来源:https://stackoverflow.com/questions/11316249/case-insensitive-rspec-match