Search code examples
ruby-on-railsrspec-rails

RSpec matching response


I am using Ruby on Rails 5 and Rspec.

My test is like

expect(json_response['data']['body']).to match(/'["can't be blank"]'/)

I am getting error

expected ["can't be blank"] to match /'["can't be blank"]'/

I was wondering, how to fix it ? Hope it is clear.


Solution

  • Reading the test failure, the JSON response returns an array with a string in it: ["can't be blank"]. Seems like a fine use case for testing equality directly:

    expect(json_response['data']['body']).to eq(["can't be blank"])
    

    match_array will work, but it "disregards differences in the ordering between the actual and expected array." As an array with one item only, that feature isn't necessary here.

    contains_exactly/match_array docs