O
O
Ord EO2021-05-11 10:32:28
ruby
Ord EO, 2021-05-11 10:32:28

How can you test FizzBuzz with Ruby's MiniTest?

There is a classic FizzBuzz

def fizz_buzz
  n = 0
  while n < 100
    n += 1
    if n % 3 == 0 && n % 5 == 0
      puts 'FizzBuzz'
    elsif n % 3 == 0
      puts 'Fizz'
    elsif n % 5 == 0
      puts 'Buzz'
    else
      puts n
    end
  end
end


How to test it with MiniTest so as not to write all 100 values ​​without decreasing n?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
oh_shi, 2021-05-11
@oh_shi

This is not a true Ruby Way FizzBuzz, it could look something like this:

puts ((1..100).map do |i|
  str = ''
  str << 'Fizz' if i % 3 == 0
  str << 'Buzz' if i % 5 == 0
  str.empty? ? i : str
end)

And for tests, you don't have to test each of the 100 values. The minimum, maximum and the test for each branch in the if are enough. It is better to avoid while and enter the required number of iterations into the method through a parameter, and then follow it through each/map.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question