2

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.

4
  • Can you add some more detail to your question? What behavior are you getting with the above code and what behavior would you like instead? Commented Nov 6, 2019 at 19:03
  • 1
    RSpec and Rubocop are two different things. What's your question? What's the problem? Commented Nov 6, 2019 at 19:03
  • It's not clear what you're asking--you don't write a test for standalone code, you write a test for a method. To test you pass all combinations of parameters to exercise the function in question. Commented Nov 6, 2019 at 19:14
  • As @Dave advises you need to write your code as a method and then perform tests on the method. For example: def m(arr1, arr2); return 'neither' if (arr1 & arr2).empty?; array2.include?('c') ? 'no' : 'yes'; end. return 'neither' if (arr1 & arr2).empty? is called a guard clause. Its use reduces by one the number of levels of nested conditional statements. array2.include?('c') ? 'no' : 'yes' uses the ternary operator. Commented Nov 7, 2019 at 0:13

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Perfectly agree: name a function and test on that function.
Thanks for making me understand principle of testing! That's why I don't see any reference regarding on what I want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.