Search code examples
ruby-on-railsrspec

Test that a substring is present in array of strings in rspec


json[:errors] = ["Username can't be blank", "Email can't be blank"]

The error, in en.yml, itself is provided as:

username: "can't be blank",
email: "can't be blank"

and the test:

expect(json[:errors]).to include t('activerecord.errors.messages.email')

Which fails because it's looking at the string "Email can't be blank", and "can't be blank" doesn't match it.

My question is what is the best (and by that I mean best practice) way to test that the substring is included in a string contained inside the array json[:errors]


Solution

  • RSpec offers a range of matchers. In this case you'll need to use the include matcher (docs) to check each element of the array. And, you'll need to use the match regex matcher (docs) to match the substring:

    expect(json[:errors]).to include(match(/can't be blank/))
    

    For readability, the match regex matcher is aliased as a_string_matching, like this:

    expect(json[:errors]).to include(a_string_matching(/can't be blank/))
    

    UPDATE:

    I just noticed that the OP's question includes an array with multiple matching elements. The include matcher checks to see if ANY elements of the array match the criteria. If you need to check that ALL elements of the array match the criteria, you can use the all matcher (docs).

    expect(json[:errors]).to all(match(/can't be blank/))