Frage

I want to check for the presence of exactly one of two possible strings in my rspec test (XOR).

Something to the effect of this:

it "worked" do
  ( 
    foo.bar.should include "A" AND foo.bar.should_not include "B" 
    ||
    foo.bar.should include "B" AND foo.bar.should_not include "A" 
  )
  # => if the above is false rspec should complain
end

Is this possible?

War es hilfreich?

Lösung

How about:

expect(foo.bar & ['A', 'B']).to have(1).item

This solution takes the array, intersects it with the possible values, and makes sure that only one element (either 'A' or 'B') is left.

@steenslag's answer fails because when rspec expectations fail, they stop the test, so "two falses don't make a true"...

If you want to use the old should syntax, it would look like this:

(foo.bar & ['A', 'B']).should have(1).item

Andere Tipps

xor is ^.

foo.bar.should(include "A") ^ foo.bar.should(include "B") 

Returns true when foo.bar includes either "A" or "B", but not both.

ar = ["AC","BC", "AB", "CC"]
ar.each{|str|p str.include?("A") ^ str.include?("B")}   
#true
#true
#false
#false
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top