Ard Enriquez
Ard Enriquez

Reputation: 23

RSpec nested if function

I'm new to RSpec and I'm trying to do testing but I have no idea how to handle nested if. I hope you can help me. Thank you!

array1 = %w[a b]
array2 = %w[aa b c]
@a = if (array1 & array2).any?
       if !array2.include? 'c'
         'yes'
       else
         'no'
            end
     else
       'neither'
     end
puts @a

I would like to develop a basic test for my code using RSpec. My code runs perfectly I just don't know how to write a test.

Upvotes: 2

Views: 226

Answers (1)

Cereal
Cereal

Reputation: 3829

You don't need to explicitly test nested if expressions. When you write a test, you're testing the code as a whole. In this case, you have 3 possible routes the code could take, in which case you would write 3 tests.

One test would satisfy (array1 & array2).any? && !array2.include?('c'), the second test would satisfy (array1 & array2).any? && array2.include?('c'), and the third test would satisfy (array1 & array2).empty?

So, for example...


def my_function(array1, array2)
  if (array1 & array2).any?
    if !array2.include? 'c'
      'yes'
    else
      'no'
    end
  else
    'neither'
  end
end

RSpec.describe 'MyFunction' do
  context 'array has c' do
    it 'should return no' do   #
      expect { my_function(['b'], ['b']) }.to eq("no")
    end
  end
end

Upvotes: 2

Related Questions