문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top