rspec - matcher for one of choices

This does work, but is unconventional because the value you pass to expect should be the value you're testing.

expect(['value1', 'value2']).to include(FooClass.new.value)

I think it would be better to do

expect(Foo.new.value).to satisfy { |value| ['value1', 'value2'].include?(value) }

This will also give you a more accurate message when your test fails.


Also, there is an or

expect('value').to eq('value1').or eq('value2')

Advantages:

  1. It sounds like normal English.
  2. The error message is a bit longer but contains all relevant info:
expected: "value1"
    got: "value"

...or:

expected: "value2"
    got: "value"
  1. As muirbot pointed out you should pass the value you are testing to expect(), not the other way.

  2. It's more flexible, it will work if someone came here looking for a solution to something like:

expect({one: 1, two: 2, three: 3}).to have_key(:one).or have_key(:first)

Use this

expect(['value1', 'value2']).to include(FooClass.new.value)

Or a simple Boolean match

expect(['value1', 'value2'].include? FooClass.new.value).to be true

Tags:

Ruby

Rspec