tim_xyz
tim_xyz

Reputation: 13491

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?

Upvotes: 1

Views: 276

Answers (2)

Hieu Pham
Hieu Pham

Reputation: 6707

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']) }

Upvotes: 2

Pavel Bulanov
Pavel Bulanov

Reputation: 953

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

Based on this link

"Compound Expectations.

Matchers can be composed using and or or to make compound expectation

Use or to chain expectations"

RSpec.describe StopLight, "#color" do
  let(:light) { StopLight.new }
  it "is green, yellow or red" do
    expect(light.color).to eq("green").or eq("yellow").or eq("red")
  end

Upvotes: 1

Related Questions