Search code examples
ruby-on-railsrspec-rails

How to use `or` in RSpec equality matchers (Rails)


I'm trying to do something like

expect(body['classification']).to (be == "Apt") || (be == "House")

Background:

This is testing a JSON API response.

Issue:

I want the test to pass if either "Apt" or "House" are returned. But in the test it is only comparing to the first value, "Apt".

Failure/Error: expect(body['classification']).to be == "Apt" or be == "House"

expected: == "Apt"
got:    "House"

Previous Solution:

There is a solution here, (Equality using OR in RSpec 2) but its depreciated now, and I wasn't able to make it work.

Documentation:

Also wasn't able to find examples like this in the documentation (https://www.relishapp.com/rspec/rspec-expectations/v/3-4/docs/built-in-matchers/equality-matchers)

Is this possible to do?


Solution

  • How about this:

    expect(body['classification'].in?(['Apt', 'Hourse']).to be_truthy
    

    Or

    expect(body['classification']).to eq('Apt').or eq('Hourse')
    

    Or even this:

    expect(body['classification']).to satify { |v| v.in?(['Apt', 'Hourse']) }