Case insensitive Rspec match

后端 未结 6 643
温柔的废话
温柔的废话 2021-02-12 10:00

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 ca

6条回答
  •  清酒与你
    2021-02-12 10:09

    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.

提交回复
热议问题